text
stringlengths 54
60.6k
|
---|
<commit_before>/*
DDS, a bridge double dummy solver.
Copyright (C) 2006-2014 by Bo Haglund /
2014-2018 by Bo Haglund & Soren Hein.
See LICENSE and README.
*/
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include "dds.h"
#include "TransTable.h"
#include "Moves.h"
#include "Memory.h"
#include "dump.h"
#define DDS_POS_LINES 5
// #define DDS_HAND_LINES 12
#define DDS_NODE_LINES 4
// #define DDS_FULL_LINE 80
#define DDS_HAND_OFFSET 16
#define DDS_HAND_OFFSET2 12
#define DDS_DIAG_WIDTH 34
string PrintSuit(const unsigned short suitCode);
void PrintDeal(
ofstream& fout,
const unsigned short ranks[][DDS_SUITS],
const unsigned spacing);
void RankToDiagrams(
unsigned short rankInSuit[DDS_HANDS][DDS_SUITS],
nodeCardsType * np,
char text[DDS_HAND_LINES][DDS_FULL_LINE]);
string WinnersToText(const unsigned short winRanks[]);
string NodeToText(nodeCardsType const * np);
string FullNodeToText(nodeCardsType const * np);
void PosToText(
pos const * posPoint,
const int target,
const int depth,
string& text);
string PrintSuit(const unsigned short suitCode)
{
if (! suitCode)
return "--";
string st;
for (int r = 14; r >= 2; r--)
if ((suitCode & bitMapRank[r]))
st += cardRank[r];
return st;
}
void PrintDeal(
ofstream& fout,
const unsigned short ranks[][DDS_SUITS],
const unsigned spacing)
{
for (int s = 0; s < DDS_SUITS; s++)
{
fout << setw(spacing) << "" <<
cardSuit[s] << " " <<
PrintSuit(ranks[0][s]) << "\n";
}
for (int s = 0; s < DDS_SUITS; s++)
{
fout << cardSuit[s] << " " <<
setw(2*spacing - 2) << left << PrintSuit(ranks[3][s]) <<
cardSuit[s] << " " <<
PrintSuit(ranks[1][s]) << "\n";
}
for (int s = 0; s < DDS_SUITS; s++)
{
fout << setw(spacing) << "" <<
cardSuit[s] << " " <<
PrintSuit(ranks[2][s]) << "\n";
}
fout << "\n";
return;
}
void RankToDiagrams(
const unsigned short rankInSuit[DDS_HANDS][DDS_SUITS],
nodeCardsType const * np,
char text[DDS_HAND_LINES][DDS_FULL_LINE])
{
int c, h, s, r;
for (int l = 0; l < DDS_HAND_LINES; l++)
{
memset(text[l], ' ', DDS_FULL_LINE);
text[l][DDS_FULL_LINE - 1] = '\0';
text[l][DDS_DIAG_WIDTH ] = '|';
}
strncpy(text[0], "Sought", 6);
strncpy(&text[0][DDS_DIAG_WIDTH + 5], "Found", 5);
for (h = 0; h < DDS_HANDS; h++)
{
int offset, line;
if (h == 0)
{
offset = DDS_HAND_OFFSET2;
line = 0;
}
else if (h == 1)
{
offset = 2 * DDS_HAND_OFFSET2;
line = 4;
}
else if (h == 2)
{
offset = DDS_HAND_OFFSET2;
line = 8;
}
else
{
offset = 0;
line = 4;
}
for (s = 0; s < DDS_SUITS; s++)
{
c = offset;
for (r = 14; r >= 2; r--)
{
if (rankInSuit[h][s] & bitMapRank[r])
{
text[line + s][c] = static_cast<char>(cardRank[r]);
text[line + s][c + DDS_DIAG_WIDTH + 5] =
(r >= 15 - np->leastWin[s] ?
static_cast<char>(cardRank[r]) : 'x');
c++;
}
}
if (c == offset)
{
text[line + s][c] = '-';
text[line + s][c + DDS_DIAG_WIDTH + 5] = '-';
c++;
}
if (h != 3)
text[line + s][c + DDS_DIAG_WIDTH + 5] = '\0';
}
}
}
string WinnersToText(const unsigned short ourWinRanks[])
{
stringstream ss;
for (int s = 0; s < DDS_SUITS; s++)
ss << cardSuit[s] << " " << PrintSuit(ourWinRanks[s]) << "\n";
return ss.str();
}
string NodeToText(nodeCardsType const * np)
{
stringstream ss;
ss << setw(16) << left << "Address" <<
static_cast<void const *>(np) << "\n";
ss << setw(16) << left << "Bounds" <<
static_cast<int>(np->lbound) << " to " <<
static_cast<int>(np->ubound) << " tricks\n";
ss << setw(16) << left << "Best move" <<
cardSuit[ static_cast<int>(np->bestMoveSuit) ] <<
cardRank[ static_cast<int>(np->bestMoveRank) ] << "\n";
return ss.str();
}
string FullNodeToText(nodeCardsType const * np)
{
stringstream ss;
vector<int> v(DDS_SUITS);
for (unsigned i = 0; i < DDS_SUITS; i++)
v[i] = 15 - static_cast<int>(np->leastWin[i]);
ss << setw(16) << left << "Lowest used" <<
cardSuit[0] << cardRank[v[0]] << ", " <<
cardSuit[1] << cardRank[v[1]] << ", " <<
cardSuit[2] << cardRank[v[2]] << ", " <<
cardSuit[3] << cardRank[v[3]] << "\n";
return NodeToText(np) + ss.str();
}
void PosToText(
pos const * posPoint,
const int target,
const int depth,
string& text)
{
stringstream ss;
ss << setw(16) << left << "Target" << target << "\n";
ss << setw(16) << "Depth" << depth << "\n";
ss << setw(16) << "tricksMAX" << posPoint->tricksMAX << "\n";
ss << setw(16) << "First hand" <<
cardHand[ posPoint->first[depth] ] << "\n";
ss << setw(16) << "Next first" <<
cardHand[ posPoint->first[depth - 1] ] << "\n";
text = ss.str();
}
int DumpInput(
const int errCode,
const deal& dl,
const int target,
const int solutions,
const int mode)
{
ofstream fout;
fout.open("dump.txt");
fout << "Error code=" << errCode << "\n\n";
fout << "Deal data:\n";
fout << "trump=";
if (dl.trump == DDS_NOTRUMP)
fout << "N\n";
else
fout << cardSuit[dl.trump] << "\n";
fout << "first=" << cardHand[dl.first] << "\n";
unsigned short ranks[4][4];
for (int k = 0; k <= 2; k++)
if (dl.currentTrickRank[k] != 0)
{
fout << "index=" << k <<
" currentTrickSuit=" << cardSuit[dl.currentTrickSuit[k]] <<
" currentTrickRank= " << cardRank[dl.currentTrickRank[k]] << "\n";
}
for (int h = 0; h < DDS_HANDS; h++)
for (int s = 0; s < DDS_SUITS; s++)
{
fout << "index1=" << h << " index2=" << s <<
" remainCards=" << dl.remainCards[h][s] << "\n";
ranks[h][s] = static_cast<unsigned short>
(dl.remainCards[h][s] >> 2);
}
fout << "\ntarget=" << target << "\n";
fout << "solutions=" << solutions << "\n";
fout << "mode=" << mode << "\n\n\n";
PrintDeal(fout, ranks, 8);
fout.close();
return 0;
}
void DumpRetrieved(
const string& fname,
pos const * posPoint,
nodeCardsType const * np,
const int target,
const int depth)
{
ofstream fout;
fout.open(fname, ofstream::out | ofstream::app);
// Big enough for all uses.
char text[DDS_HAND_LINES][DDS_FULL_LINE];
fout << "Retrieved entry\n";
fout << string(15, '-') << "\n";
string stext;
PosToText(posPoint, target, depth, stext);
fout << stext << "\n";
fout << FullNodeToText(np) << "\n";
RankToDiagrams(posPoint->rankInSuit, np, text);
for (int i = 0; i < DDS_HAND_LINES; i++)
fout << string(text[i]) << "\n";
fout << "\n";
fout.close();
}
void DumpStored(
const string& fname,
pos const * posPoint,
Moves const * moves,
nodeCardsType const * np,
const int target,
const int depth)
{
ofstream fout;
fout.open(fname, ofstream::out | ofstream::app);
// Big enough for all uses.
char text[DDS_HAND_LINES][DDS_FULL_LINE];
fout << "Stored entry\n";
fout << string(12, '-') << "\n";
string stext;
PosToText(posPoint, target, depth, stext);
fout << stext << "\n";
fout << NodeToText(np);
moves->TrickToText((depth >> 2) + 1, text[0]);
fout << string(text[0]) << "\n";
PrintDeal(fout, posPoint->rankInSuit, 16);
fout.close();
}
void DumpTopLevel(
ThreadData const * thrp,
const int tricks,
const int lower,
const int upper,
const int printMode)
{
ofstream fout;
fout.open(thrp->fnTopLevel, ofstream::out | ofstream::app);
char text[DDS_HAND_LINES][DDS_FULL_LINE];
pos const * posPoint = &thrp->lookAheadPos;
if (printMode == 0)
{
// Trying just one target.
sprintf(text[0], "Single target %d, %s\n",
tricks,
"achieved");
}
else if (printMode == 1)
{
// Looking for best score.
if (thrp->val)
{
sprintf(text[0],
"Loop target %d, bounds %d .. %d, achieved with move %c%c\n",
tricks,
lower,
upper,
cardSuit[ thrp->bestMove[thrp->iniDepth].suit ],
cardRank[ thrp->bestMove[thrp->iniDepth].rank ]);
}
else
{
sprintf(text[0],
"Loop target %d, bounds %d .. %d, failed\n",
tricks,
lower,
upper);
}
}
else if (printMode == 2)
{
// Looking for other moves with best score.
if (thrp->val)
{
sprintf(text[0],
"Loop for cards with score %d, achieved with move %c%c\n",
tricks,
cardSuit[ thrp->bestMove[thrp->iniDepth].suit ],
cardRank[ thrp->bestMove[thrp->iniDepth].rank ]);
}
else
{
sprintf(text[0],
"Loop for cards with score %d, failed\n",
tricks);
}
}
size_t l = strlen(text[0]) - 1;
memset(text[1], '-', l);
text[1][l] = '\0';
fout << string(text[0]) << string(text[1]) << "\n\n";
PrintDeal(fout, posPoint->rankInSuit, 16);
fout << WinnersToText(posPoint->winRanks[ thrp->iniDepth ]) << "\n";
fout << thrp->nodes << " AB nodes, " <<
thrp->trickNodes << " trick nodes\n\n";
fout.close();
}
<commit_msg>More refactoring<commit_after>/*
DDS, a bridge double dummy solver.
Copyright (C) 2006-2014 by Bo Haglund /
2014-2018 by Bo Haglund & Soren Hein.
See LICENSE and README.
*/
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include "dds.h"
#include "TransTable.h"
#include "Moves.h"
#include "Memory.h"
#include "dump.h"
#define DDS_POS_LINES 5
// #define DDS_HAND_LINES 12
#define DDS_NODE_LINES 4
// #define DDS_FULL_LINE 80
#define DDS_HAND_OFFSET 16
#define DDS_HAND_OFFSET2 12
#define DDS_DIAG_WIDTH 34
string PrintSuit(const unsigned short suitCode);
void PrintDeal(
ofstream& fout,
const unsigned short ranks[][DDS_SUITS],
const unsigned spacing);
void RankToDiagrams(
unsigned short rankInSuit[DDS_HANDS][DDS_SUITS],
nodeCardsType * np,
char text[DDS_HAND_LINES][DDS_FULL_LINE]);
string WinnersToText(const unsigned short winRanks[]);
string NodeToText(nodeCardsType const * np);
string FullNodeToText(nodeCardsType const * np);
string PosToText(
pos const * posPoint,
const int target,
const int depth);
string TopMove(
const bool val,
const moveType& bestMove);
string PrintSuit(const unsigned short suitCode)
{
if (! suitCode)
return "--";
string st;
for (int r = 14; r >= 2; r--)
if ((suitCode & bitMapRank[r]))
st += cardRank[r];
return st;
}
void PrintDeal(
ofstream& fout,
const unsigned short ranks[][DDS_SUITS],
const unsigned spacing)
{
for (int s = 0; s < DDS_SUITS; s++)
{
fout << setw(spacing) << "" <<
cardSuit[s] << " " <<
PrintSuit(ranks[0][s]) << "\n";
}
for (int s = 0; s < DDS_SUITS; s++)
{
fout << cardSuit[s] << " " <<
setw(2*spacing - 2) << left << PrintSuit(ranks[3][s]) <<
cardSuit[s] << " " <<
PrintSuit(ranks[1][s]) << "\n";
}
for (int s = 0; s < DDS_SUITS; s++)
{
fout << setw(spacing) << "" <<
cardSuit[s] << " " <<
PrintSuit(ranks[2][s]) << "\n";
}
fout << "\n";
return;
}
void RankToDiagrams(
const unsigned short rankInSuit[DDS_HANDS][DDS_SUITS],
nodeCardsType const * np,
char text[DDS_HAND_LINES][DDS_FULL_LINE])
{
int c, h, s, r;
for (int l = 0; l < DDS_HAND_LINES; l++)
{
memset(text[l], ' ', DDS_FULL_LINE);
text[l][DDS_FULL_LINE - 1] = '\0';
text[l][DDS_DIAG_WIDTH ] = '|';
}
strncpy(text[0], "Sought", 6);
strncpy(&text[0][DDS_DIAG_WIDTH + 5], "Found", 5);
for (h = 0; h < DDS_HANDS; h++)
{
int offset, line;
if (h == 0)
{
offset = DDS_HAND_OFFSET2;
line = 0;
}
else if (h == 1)
{
offset = 2 * DDS_HAND_OFFSET2;
line = 4;
}
else if (h == 2)
{
offset = DDS_HAND_OFFSET2;
line = 8;
}
else
{
offset = 0;
line = 4;
}
for (s = 0; s < DDS_SUITS; s++)
{
c = offset;
for (r = 14; r >= 2; r--)
{
if (rankInSuit[h][s] & bitMapRank[r])
{
text[line + s][c] = static_cast<char>(cardRank[r]);
text[line + s][c + DDS_DIAG_WIDTH + 5] =
(r >= 15 - np->leastWin[s] ?
static_cast<char>(cardRank[r]) : 'x');
c++;
}
}
if (c == offset)
{
text[line + s][c] = '-';
text[line + s][c + DDS_DIAG_WIDTH + 5] = '-';
c++;
}
if (h != 3)
text[line + s][c + DDS_DIAG_WIDTH + 5] = '\0';
}
}
}
string WinnersToText(const unsigned short ourWinRanks[])
{
stringstream ss;
for (int s = 0; s < DDS_SUITS; s++)
ss << cardSuit[s] << " " << PrintSuit(ourWinRanks[s]) << "\n";
return ss.str();
}
string NodeToText(nodeCardsType const * np)
{
stringstream ss;
ss << setw(16) << left << "Address" <<
static_cast<void const *>(np) << "\n";
ss << setw(16) << left << "Bounds" <<
static_cast<int>(np->lbound) << " to " <<
static_cast<int>(np->ubound) << " tricks\n";
ss << setw(16) << left << "Best move" <<
cardSuit[ static_cast<int>(np->bestMoveSuit) ] <<
cardRank[ static_cast<int>(np->bestMoveRank) ] << "\n";
return ss.str();
}
string FullNodeToText(nodeCardsType const * np)
{
stringstream ss;
vector<int> v(DDS_SUITS);
for (unsigned i = 0; i < DDS_SUITS; i++)
v[i] = 15 - static_cast<int>(np->leastWin[i]);
ss << setw(16) << left << "Lowest used" <<
cardSuit[0] << cardRank[v[0]] << ", " <<
cardSuit[1] << cardRank[v[1]] << ", " <<
cardSuit[2] << cardRank[v[2]] << ", " <<
cardSuit[3] << cardRank[v[3]] << "\n";
return NodeToText(np) + ss.str();
}
string PosToText(
pos const * posPoint,
const int target,
const int depth)
{
stringstream ss;
ss << setw(16) << left << "Target" << target << "\n";
ss << setw(16) << "Depth" << depth << "\n";
ss << setw(16) << "tricksMAX" << posPoint->tricksMAX << "\n";
ss << setw(16) << "First hand" <<
cardHand[ posPoint->first[depth] ] << "\n";
ss << setw(16) << "Next first" <<
cardHand[ posPoint->first[depth - 1] ] << "\n";
return ss.str();
}
int DumpInput(
const int errCode,
const deal& dl,
const int target,
const int solutions,
const int mode)
{
ofstream fout;
fout.open("dump.txt");
fout << "Error code=" << errCode << "\n\n";
fout << "Deal data:\n";
fout << "trump=";
if (dl.trump == DDS_NOTRUMP)
fout << "N\n";
else
fout << cardSuit[dl.trump] << "\n";
fout << "first=" << cardHand[dl.first] << "\n";
unsigned short ranks[4][4];
for (int k = 0; k <= 2; k++)
if (dl.currentTrickRank[k] != 0)
{
fout << "index=" << k <<
" currentTrickSuit=" << cardSuit[dl.currentTrickSuit[k]] <<
" currentTrickRank= " << cardRank[dl.currentTrickRank[k]] << "\n";
}
for (int h = 0; h < DDS_HANDS; h++)
for (int s = 0; s < DDS_SUITS; s++)
{
fout << "index1=" << h << " index2=" << s <<
" remainCards=" << dl.remainCards[h][s] << "\n";
ranks[h][s] = static_cast<unsigned short>
(dl.remainCards[h][s] >> 2);
}
fout << "\ntarget=" << target << "\n";
fout << "solutions=" << solutions << "\n";
fout << "mode=" << mode << "\n\n\n";
PrintDeal(fout, ranks, 8);
fout.close();
return 0;
}
void DumpRetrieved(
const string& fname,
pos const * posPoint,
nodeCardsType const * np,
const int target,
const int depth)
{
ofstream fout;
fout.open(fname, ofstream::out | ofstream::app);
// Big enough for all uses.
char text[DDS_HAND_LINES][DDS_FULL_LINE];
fout << "Retrieved entry\n";
fout << string(15, '-') << "\n";
fout << PosToText(posPoint, target, depth) << "\n";
fout << FullNodeToText(np) << "\n";
RankToDiagrams(posPoint->rankInSuit, np, text);
for (int i = 0; i < DDS_HAND_LINES; i++)
fout << string(text[i]) << "\n";
fout << "\n";
fout.close();
}
void DumpStored(
const string& fname,
pos const * posPoint,
Moves const * moves,
nodeCardsType const * np,
const int target,
const int depth)
{
ofstream fout;
fout.open(fname, ofstream::out | ofstream::app);
// Big enough for all uses.
char text[DDS_HAND_LINES][DDS_FULL_LINE];
fout << "Stored entry\n";
fout << string(12, '-') << "\n";
fout << PosToText(posPoint, target, depth) << "\n";
fout << NodeToText(np);
moves->TrickToText((depth >> 2) + 1, text[0]);
fout << string(text[0]) << "\n";
PrintDeal(fout, posPoint->rankInSuit, 16);
fout.close();
}
string TopMove(
const bool val,
const moveType& bestMove)
{
if (val)
{
stringstream ss;
ss << "achieved with move " <<
cardSuit[ bestMove.suit ] <<
cardRank[ bestMove.rank ];
return ss.str();
}
else
return "failed";
}
void DumpTopLevel(
ThreadData const * thrp,
const int tricks,
const int lower,
const int upper,
const int printMode)
{
ofstream fout;
fout.open(thrp->fnTopLevel, ofstream::out | ofstream::app);
pos const * posPoint = &thrp->lookAheadPos;
string stext;
if (printMode == 0)
{
// Trying just one target.
stext = "Single target " + to_string(tricks) + ", " + "achieved";
}
else if (printMode == 1)
{
// Looking for best score.
stext = "Loop target " + to_string(tricks) + ", " +
"bounds " + to_string(lower) + " .. " + to_string(upper) + ", " +
TopMove(thrp->val, thrp->bestMove[thrp->iniDepth]) + "";
}
else if (printMode == 2)
{
// Looking for other moves with best score.
stext = "Loop for cards with score " + to_string(tricks) + ", " +
TopMove(thrp->val, thrp->bestMove[thrp->iniDepth]);
}
fout << stext << "\n" << string(stext.size(), '-') << "\n\n";
PrintDeal(fout, posPoint->rankInSuit, 16);
fout << WinnersToText(posPoint->winRanks[ thrp->iniDepth ]) << "\n";
fout << thrp->nodes << " AB nodes, " <<
thrp->trickNodes << " trick nodes\n\n";
fout.close();
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright RTK Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "rtkConjugateGradientConeBeamReconstructionFilter.h"
namespace rtk
{
template<>
ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
::ConjugateGradientConeBeamReconstructionFilter()
{
this->SetNumberOfRequiredInputs(3);
// Set the default values of member parameters
m_NumberOfIterations=3;
m_MeasureExecutionTimes=false;
// m_IterationCosts=false;
m_Gamma = 0;
m_Regularized = false;
m_CudaConjugateGradient = true;
m_DisableDisplacedDetectorFilter = false;
// Create the filters
#ifdef RTK_USE_CUDA
m_DisplacedDetectorFilter = rtk::CudaDisplacedDetectorImageFilter::New();
m_ConstantVolumeSource = rtk::CudaConstantVolumeSource::New();
#else
m_DisplacedDetectorFilter = DisplacedDetectorFilterType::New();
m_ConstantVolumeSource = ConstantImageSourceType::New();
#endif
m_CGOperator = CGOperatorFilterType::New();
m_MultiplyVolumeFilter = MultiplyFilterType::New();
m_MatrixVectorMultiplyFilter = MatrixVectorMultiplyFilterType::New();
m_MultiplyOutputFilter = MultiplyFilterType::New();
// Set permanent parameters
m_ConstantVolumeSource->SetConstant(0);
m_DisplacedDetectorFilter->SetPadOnTruncatedSide(false);
}
//template<>
//void
//ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
//::SetSupportMask(const itk::Image<float, 3> *SupportMask)
//{
// this->SetInput("SupportMask", const_cast<itk::Image<float, 3>*>(SupportMask));
//}
//template<>
//typename itk::Image<float, 3>::ConstPointer
//ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
//::GetSupportMask()
//{
// return static_cast< const itk::Image<float, 3> * >
// ( this->itk::ProcessObject::GetInput("SupportMask") );
//}
template<>
void
ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
::GenerateOutputInformation()
{
// Choose between cuda or non-cuda conjugate gradient filter
m_ConjugateGradientFilter = ConjugateGradientFilterType::New();
#ifdef RTK_USE_CUDA
if (m_CudaConjugateGradient)
m_ConjugateGradientFilter = rtk::CudaConjugateGradientImageFilter_3f::New();
#endif
m_ConjugateGradientFilter->SetA(m_CGOperator.GetPointer());
m_ConjugateGradientFilter->SetTargetSumOfSquaresBetweenConsecutiveIterates(m_TargetSumOfSquaresBetweenConsecutiveIterates);
// m_ConjugateGradientFilter->SetIterationCosts(m_IterationCosts);
// Set runtime connections
m_ConstantVolumeSource->SetInformationFromImage(this->GetInput(0));
m_CGOperator->SetInput(1, this->GetInput(1));
m_CGOperator->SetSupportMask(this->GetSupportMask());
m_ConjugateGradientFilter->SetX(this->GetInput(0));
m_DisplacedDetectorFilter->SetDisable(m_DisableDisplacedDetectorFilter);
m_DisplacedDetectorFilter->SetInput(this->GetInput(2));
// Links with the m_BackProjectionFilter should be set here and not
// in the constructor, as m_BackProjectionFilter is set at runtime
m_BackProjectionFilterForB->SetInput(0, m_ConstantVolumeSource->GetOutput());
m_ConjugateGradientFilter->SetB(m_BackProjectionFilterForB->GetOutput());
// Set the matrix vector multiply filter's inputs for multiplication
// by the inverse covariance matrix (for GLS minimization)
m_MatrixVectorMultiplyFilter->SetInput1(this->GetInput(1));
m_MatrixVectorMultiplyFilter->SetInput2(m_DisplacedDetectorFilter->GetOutput());
m_CGOperator->SetInput(2, m_DisplacedDetectorFilter->GetOutput());
m_BackProjectionFilterForB->SetInput(1, m_MatrixVectorMultiplyFilter->GetOutput());
// If a support mask is used, it serves as preconditioning weights
if (this->GetSupportMask().IsNotNull())
{
// Multiply the volume by support mask, and pass it to the conjugate gradient operator
m_MultiplyVolumeFilter->SetInput1(m_BackProjectionFilterForB->GetOutput());
m_MultiplyVolumeFilter->SetInput2(this->GetSupportMask());
m_CGOperator->SetSupportMask(this->GetSupportMask());
m_ConjugateGradientFilter->SetB(m_MultiplyVolumeFilter->GetOutput());
// Multiply the output by the support mask
m_MultiplyOutputFilter->SetInput1(m_ConjugateGradientFilter->GetOutput());
m_MultiplyOutputFilter->SetInput2(this->GetSupportMask());
}
// For the same reason, set geometry now
m_CGOperator->SetGeometry(this->m_Geometry);
m_BackProjectionFilterForB->SetGeometry(this->m_Geometry.GetPointer());
m_DisplacedDetectorFilter->SetGeometry(this->m_Geometry);
// Set runtime parameters
m_ConjugateGradientFilter->SetNumberOfIterations(this->m_NumberOfIterations);
m_CGOperator->SetGamma(m_Gamma);
m_CGOperator->SetTikhonov(m_Tikhonov);
// Set memory management parameters
m_MatrixVectorMultiplyFilter->ReleaseDataFlagOn();
m_BackProjectionFilterForB->ReleaseDataFlagOn();
if (this->GetSupportMask().IsNotNull())
{
m_MultiplyVolumeFilter->ReleaseDataFlagOn();
m_MultiplyOutputFilter->ReleaseDataFlagOn();
}
// Have the last filter calculate its output information
m_ConjugateGradientFilter->UpdateOutputInformation();
// Copy it as the output information of the composite filter
this->GetOutput()->CopyInformation( m_ConjugateGradientFilter->GetOutput() );
}
template<>
void
ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
::GenerateData()
{
itk::TimeProbe ConjugateGradientTimeProbe;
// typename StatisticsImageFilterType::Pointer StatisticsImageFilterForC = StatisticsImageFilterType::New();
// typename MultiplyFilterType::Pointer MultiplyFilterForC = MultiplyFilterType::New();
// if (m_IterationCosts)
// {
// MultiplyFilterForC->SetInput(0,this->GetInput(1));
// MultiplyFilterForC->SetInput(1,this->GetInput(2));
// MultiplyFilterForC->Update();
// MultiplyFilterForC->SetInput(1,MultiplyFilterForC->GetOutput());
// MultiplyFilterForC->Update();
// StatisticsImageFilterForC->SetInput(MultiplyFilterForC->GetOutput());
// StatisticsImageFilterForC->Update();
// m_ConjugateGradientFilter->SetC(0.5*StatisticsImageFilterForC->GetSum());
// }
if(m_MeasureExecutionTimes)
{
std::cout << "Starting ConjugateGradient" << std::endl;
ConjugateGradientTimeProbe.Start();
}
m_ConjugateGradientFilter->Update();
if (this->GetSupportMask())
{
m_MultiplyOutputFilter->Update();
}
if(m_MeasureExecutionTimes)
{
ConjugateGradientTimeProbe.Stop();
std::cout << "ConjugateGradient took " << ConjugateGradientTimeProbe.GetTotal() << ' ' << ConjugateGradientTimeProbe.GetUnit() << std::endl;
}
if (this->GetSupportMask())
{
this->GraftOutput( m_MultiplyOutputFilter->GetOutput() );
}
else
{
this->GraftOutput( m_ConjugateGradientFilter->GetOutput() );
}
}
} // end namespace rtk
<commit_msg>Fixed uninitialized variable<commit_after>/*=========================================================================
*
* Copyright RTK Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "rtkConjugateGradientConeBeamReconstructionFilter.h"
namespace rtk
{
template<>
ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
::ConjugateGradientConeBeamReconstructionFilter()
{
this->SetNumberOfRequiredInputs(3);
// Set the default values of member parameters
m_NumberOfIterations=3;
m_MeasureExecutionTimes=false;
// m_IterationCosts=false;
m_Gamma = 0;
m_Tikhonov = 0;
m_Regularized = false;
m_CudaConjugateGradient = true;
m_DisableDisplacedDetectorFilter = false;
m_TargetSumOfSquaresBetweenConsecutiveIterates = 0;
// Create the filters
#ifdef RTK_USE_CUDA
m_DisplacedDetectorFilter = rtk::CudaDisplacedDetectorImageFilter::New();
m_ConstantVolumeSource = rtk::CudaConstantVolumeSource::New();
#else
m_DisplacedDetectorFilter = DisplacedDetectorFilterType::New();
m_ConstantVolumeSource = ConstantImageSourceType::New();
#endif
m_CGOperator = CGOperatorFilterType::New();
m_MultiplyVolumeFilter = MultiplyFilterType::New();
m_MatrixVectorMultiplyFilter = MatrixVectorMultiplyFilterType::New();
m_MultiplyOutputFilter = MultiplyFilterType::New();
// Set permanent parameters
m_ConstantVolumeSource->SetConstant(0);
m_DisplacedDetectorFilter->SetPadOnTruncatedSide(false);
}
//template<>
//void
//ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
//::SetSupportMask(const itk::Image<float, 3> *SupportMask)
//{
// this->SetInput("SupportMask", const_cast<itk::Image<float, 3>*>(SupportMask));
//}
//template<>
//typename itk::Image<float, 3>::ConstPointer
//ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
//::GetSupportMask()
//{
// return static_cast< const itk::Image<float, 3> * >
// ( this->itk::ProcessObject::GetInput("SupportMask") );
//}
template<>
void
ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
::GenerateOutputInformation()
{
// Choose between cuda or non-cuda conjugate gradient filter
m_ConjugateGradientFilter = ConjugateGradientFilterType::New();
#ifdef RTK_USE_CUDA
if (m_CudaConjugateGradient)
m_ConjugateGradientFilter = rtk::CudaConjugateGradientImageFilter_3f::New();
#endif
m_ConjugateGradientFilter->SetA(m_CGOperator.GetPointer());
m_ConjugateGradientFilter->SetTargetSumOfSquaresBetweenConsecutiveIterates(m_TargetSumOfSquaresBetweenConsecutiveIterates);
// m_ConjugateGradientFilter->SetIterationCosts(m_IterationCosts);
// Set runtime connections
m_ConstantVolumeSource->SetInformationFromImage(this->GetInput(0));
m_CGOperator->SetInput(1, this->GetInput(1));
m_CGOperator->SetSupportMask(this->GetSupportMask());
m_ConjugateGradientFilter->SetX(this->GetInput(0));
m_DisplacedDetectorFilter->SetDisable(m_DisableDisplacedDetectorFilter);
m_DisplacedDetectorFilter->SetInput(this->GetInput(2));
// Links with the m_BackProjectionFilter should be set here and not
// in the constructor, as m_BackProjectionFilter is set at runtime
m_BackProjectionFilterForB->SetInput(0, m_ConstantVolumeSource->GetOutput());
m_ConjugateGradientFilter->SetB(m_BackProjectionFilterForB->GetOutput());
// Set the matrix vector multiply filter's inputs for multiplication
// by the inverse covariance matrix (for GLS minimization)
m_MatrixVectorMultiplyFilter->SetInput1(this->GetInput(1));
m_MatrixVectorMultiplyFilter->SetInput2(m_DisplacedDetectorFilter->GetOutput());
m_CGOperator->SetInput(2, m_DisplacedDetectorFilter->GetOutput());
m_BackProjectionFilterForB->SetInput(1, m_MatrixVectorMultiplyFilter->GetOutput());
// If a support mask is used, it serves as preconditioning weights
if (this->GetSupportMask().IsNotNull())
{
// Multiply the volume by support mask, and pass it to the conjugate gradient operator
m_MultiplyVolumeFilter->SetInput1(m_BackProjectionFilterForB->GetOutput());
m_MultiplyVolumeFilter->SetInput2(this->GetSupportMask());
m_CGOperator->SetSupportMask(this->GetSupportMask());
m_ConjugateGradientFilter->SetB(m_MultiplyVolumeFilter->GetOutput());
// Multiply the output by the support mask
m_MultiplyOutputFilter->SetInput1(m_ConjugateGradientFilter->GetOutput());
m_MultiplyOutputFilter->SetInput2(this->GetSupportMask());
}
// For the same reason, set geometry now
m_CGOperator->SetGeometry(this->m_Geometry);
m_BackProjectionFilterForB->SetGeometry(this->m_Geometry.GetPointer());
m_DisplacedDetectorFilter->SetGeometry(this->m_Geometry);
// Set runtime parameters
m_ConjugateGradientFilter->SetNumberOfIterations(this->m_NumberOfIterations);
m_CGOperator->SetGamma(m_Gamma);
m_CGOperator->SetTikhonov(m_Tikhonov);
// Set memory management parameters
m_MatrixVectorMultiplyFilter->ReleaseDataFlagOn();
m_BackProjectionFilterForB->ReleaseDataFlagOn();
if (this->GetSupportMask().IsNotNull())
{
m_MultiplyVolumeFilter->ReleaseDataFlagOn();
m_MultiplyOutputFilter->ReleaseDataFlagOn();
}
// Have the last filter calculate its output information
m_ConjugateGradientFilter->UpdateOutputInformation();
// Copy it as the output information of the composite filter
this->GetOutput()->CopyInformation( m_ConjugateGradientFilter->GetOutput() );
}
template<>
void
ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >
::GenerateData()
{
itk::TimeProbe ConjugateGradientTimeProbe;
// typename StatisticsImageFilterType::Pointer StatisticsImageFilterForC = StatisticsImageFilterType::New();
// typename MultiplyFilterType::Pointer MultiplyFilterForC = MultiplyFilterType::New();
// if (m_IterationCosts)
// {
// MultiplyFilterForC->SetInput(0,this->GetInput(1));
// MultiplyFilterForC->SetInput(1,this->GetInput(2));
// MultiplyFilterForC->Update();
// MultiplyFilterForC->SetInput(1,MultiplyFilterForC->GetOutput());
// MultiplyFilterForC->Update();
// StatisticsImageFilterForC->SetInput(MultiplyFilterForC->GetOutput());
// StatisticsImageFilterForC->Update();
// m_ConjugateGradientFilter->SetC(0.5*StatisticsImageFilterForC->GetSum());
// }
if(m_MeasureExecutionTimes)
{
std::cout << "Starting ConjugateGradient" << std::endl;
ConjugateGradientTimeProbe.Start();
}
m_ConjugateGradientFilter->Update();
if (this->GetSupportMask())
{
m_MultiplyOutputFilter->Update();
}
if(m_MeasureExecutionTimes)
{
ConjugateGradientTimeProbe.Stop();
std::cout << "ConjugateGradient took " << ConjugateGradientTimeProbe.GetTotal() << ' ' << ConjugateGradientTimeProbe.GetUnit() << std::endl;
}
if (this->GetSupportMask())
{
this->GraftOutput( m_MultiplyOutputFilter->GetOutput() );
}
else
{
this->GraftOutput( m_ConjugateGradientFilter->GetOutput() );
}
}
} // end namespace rtk
<|endoftext|> |
<commit_before><commit_msg>coverity#1078582 Dereference after null check<commit_after><|endoftext|> |
<commit_before>// Copyright 2019 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 "net/third_party/quiche/src/quic/core/http/quic_receive_control_stream.h"
#include "net/third_party/quiche/src/quic/core/quic_utils.h"
#include "net/third_party/quiche/src/quic/test_tools/quic_spdy_session_peer.h"
#include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
namespace quic {
namespace test {
namespace {
using ::testing::_;
using ::testing::StrictMock;
struct TestParams {
TestParams(const ParsedQuicVersion& version, Perspective perspective)
: version(version), perspective(perspective) {
QUIC_LOG(INFO) << "TestParams: version: "
<< ParsedQuicVersionToString(version)
<< ", perspective: " << perspective;
}
TestParams(const TestParams& other)
: version(other.version), perspective(other.perspective) {}
ParsedQuicVersion version;
Perspective perspective;
};
std::vector<TestParams> GetTestParams() {
std::vector<TestParams> params;
ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
for (const auto& version : AllSupportedVersions()) {
if (!VersionHasStreamType(version.transport_version)) {
continue;
}
for (Perspective p : {Perspective::IS_SERVER, Perspective::IS_CLIENT}) {
params.emplace_back(version, p);
}
}
return params;
}
class QuicReceiveControlStreamTest : public QuicTestWithParam<TestParams> {
public:
QuicReceiveControlStreamTest()
: connection_(new StrictMock<MockQuicConnection>(
&helper_,
&alarm_factory_,
perspective(),
SupportedVersions(GetParam().version))),
session_(connection_) {
session_.Initialize();
auto pending = QuicMakeUnique<PendingStream>(
QuicUtils::GetFirstUnidirectionalStreamId(
GetParam().version.transport_version,
perspective() == Perspective::IS_CLIENT ? Perspective::IS_SERVER
: Perspective::IS_CLIENT),
&session_);
receive_control_stream_ =
QuicMakeUnique<QuicReceiveControlStream>(pending.get());
}
Perspective perspective() const { return GetParam().perspective; }
std::string EncodeSettings(const SettingsFrame& settings) {
HttpEncoder encoder;
std::unique_ptr<char[]> buffer;
auto header_length = encoder.SerializeSettingsFrame(settings, &buffer);
return std::string(buffer.get(), header_length);
}
MockQuicConnectionHelper helper_;
MockAlarmFactory alarm_factory_;
StrictMock<MockQuicConnection>* connection_;
StrictMock<MockQuicSpdySession> session_;
HttpDecoder decoder_;
std::unique_ptr<QuicReceiveControlStream> receive_control_stream_;
};
INSTANTIATE_TEST_SUITE_P(Tests,
QuicReceiveControlStreamTest,
::testing::ValuesIn(GetTestParams()));
TEST_P(QuicReceiveControlStreamTest, ResetControlStream) {
EXPECT_TRUE(receive_control_stream_->is_static());
QuicRstStreamFrame rst_frame(kInvalidControlFrameId,
receive_control_stream_->id(),
QUIC_STREAM_CANCELLED, 1234);
EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_STREAM_ID, _, _));
receive_control_stream_->OnStreamReset(rst_frame);
}
TEST_P(QuicReceiveControlStreamTest, ReceiveSettings) {
SettingsFrame settings;
settings.values[3] = 2;
settings.values[kSettingsMaxHeaderListSize] = 5;
std::string data = EncodeSettings(settings);
QuicStreamFrame frame(receive_control_stream_->id(), false, 0,
QuicStringPiece(data));
EXPECT_NE(5u, session_.max_outbound_header_list_size());
receive_control_stream_->OnStreamFrame(frame);
EXPECT_EQ(5u, session_.max_outbound_header_list_size());
}
TEST_P(QuicReceiveControlStreamTest, ReceiveSettingsTwice) {
SettingsFrame settings;
settings.values[3] = 2;
settings.values[kSettingsMaxHeaderListSize] = 5;
std::string data = EncodeSettings(settings);
QuicStreamFrame frame(receive_control_stream_->id(), false, 0,
QuicStringPiece(data));
QuicStreamFrame frame2(receive_control_stream_->id(), false, data.length(),
QuicStringPiece(data));
receive_control_stream_->OnStreamFrame(frame);
EXPECT_CALL(*connection_,
CloseConnection(QUIC_INVALID_STREAM_ID,
"Settings frames are received twice.", _));
receive_control_stream_->OnStreamFrame(frame2);
}
TEST_P(QuicReceiveControlStreamTest, ReceiveSettingsFragments) {
SettingsFrame settings;
settings.values[3] = 2;
settings.values[kSettingsMaxHeaderListSize] = 5;
std::string data = EncodeSettings(settings);
std::string data1 = data.substr(0, 1);
std::string data2 = data.substr(1, data.length() - 1);
QuicStreamFrame frame(receive_control_stream_->id(), false, 0,
QuicStringPiece(data.data(), 1));
QuicStreamFrame frame2(receive_control_stream_->id(), false, 1,
QuicStringPiece(data.data() + 1, data.length() - 1));
EXPECT_NE(5u, session_.max_outbound_header_list_size());
receive_control_stream_->OnStreamFrame(frame);
receive_control_stream_->OnStreamFrame(frame2);
EXPECT_EQ(5u, session_.max_outbound_header_list_size());
}
TEST_P(QuicReceiveControlStreamTest, ReceiveWrongFrame) {
GoAwayFrame goaway;
goaway.stream_id = 0x1;
HttpEncoder encoder;
std::unique_ptr<char[]> buffer;
QuicByteCount header_length = encoder.SerializeGoAwayFrame(goaway, &buffer);
std::string data = std::string(buffer.get(), header_length);
QuicStreamFrame frame(receive_control_stream_->id(), false, 0,
QuicStringPiece(data));
EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_DECODER_ERROR, _, _));
receive_control_stream_->OnStreamFrame(frame);
}
} // namespace
} // namespace test
} // namespace quic
<commit_msg>Add test to ensure that a push promise on a control stream closes the connection.<commit_after>// Copyright 2019 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 "net/third_party/quiche/src/quic/core/http/quic_receive_control_stream.h"
#include "net/third_party/quiche/src/quic/core/quic_utils.h"
#include "net/third_party/quiche/src/quic/test_tools/quic_spdy_session_peer.h"
#include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
namespace quic {
namespace test {
namespace {
using ::testing::_;
using ::testing::AtLeast;
using ::testing::StrictMock;
struct TestParams {
TestParams(const ParsedQuicVersion& version, Perspective perspective)
: version(version), perspective(perspective) {
QUIC_LOG(INFO) << "TestParams: version: "
<< ParsedQuicVersionToString(version)
<< ", perspective: " << perspective;
}
TestParams(const TestParams& other)
: version(other.version), perspective(other.perspective) {}
ParsedQuicVersion version;
Perspective perspective;
};
std::vector<TestParams> GetTestParams() {
std::vector<TestParams> params;
ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
for (const auto& version : AllSupportedVersions()) {
if (!VersionHasStreamType(version.transport_version)) {
continue;
}
for (Perspective p : {Perspective::IS_SERVER, Perspective::IS_CLIENT}) {
params.emplace_back(version, p);
}
}
return params;
}
class QuicReceiveControlStreamTest : public QuicTestWithParam<TestParams> {
public:
QuicReceiveControlStreamTest()
: connection_(new StrictMock<MockQuicConnection>(
&helper_,
&alarm_factory_,
perspective(),
SupportedVersions(GetParam().version))),
session_(connection_) {
session_.Initialize();
auto pending = QuicMakeUnique<PendingStream>(
QuicUtils::GetFirstUnidirectionalStreamId(
GetParam().version.transport_version,
perspective() == Perspective::IS_CLIENT ? Perspective::IS_SERVER
: Perspective::IS_CLIENT),
&session_);
receive_control_stream_ =
QuicMakeUnique<QuicReceiveControlStream>(pending.get());
}
Perspective perspective() const { return GetParam().perspective; }
std::string EncodeSettings(const SettingsFrame& settings) {
HttpEncoder encoder;
std::unique_ptr<char[]> buffer;
auto header_length = encoder.SerializeSettingsFrame(settings, &buffer);
return std::string(buffer.get(), header_length);
}
MockQuicConnectionHelper helper_;
MockAlarmFactory alarm_factory_;
StrictMock<MockQuicConnection>* connection_;
StrictMock<MockQuicSpdySession> session_;
HttpDecoder decoder_;
std::unique_ptr<QuicReceiveControlStream> receive_control_stream_;
};
INSTANTIATE_TEST_SUITE_P(Tests,
QuicReceiveControlStreamTest,
::testing::ValuesIn(GetTestParams()));
TEST_P(QuicReceiveControlStreamTest, ResetControlStream) {
EXPECT_TRUE(receive_control_stream_->is_static());
QuicRstStreamFrame rst_frame(kInvalidControlFrameId,
receive_control_stream_->id(),
QUIC_STREAM_CANCELLED, 1234);
EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_STREAM_ID, _, _));
receive_control_stream_->OnStreamReset(rst_frame);
}
TEST_P(QuicReceiveControlStreamTest, ReceiveSettings) {
SettingsFrame settings;
settings.values[3] = 2;
settings.values[kSettingsMaxHeaderListSize] = 5;
std::string data = EncodeSettings(settings);
QuicStreamFrame frame(receive_control_stream_->id(), false, 0,
QuicStringPiece(data));
EXPECT_NE(5u, session_.max_outbound_header_list_size());
receive_control_stream_->OnStreamFrame(frame);
EXPECT_EQ(5u, session_.max_outbound_header_list_size());
}
TEST_P(QuicReceiveControlStreamTest, ReceiveSettingsTwice) {
SettingsFrame settings;
settings.values[3] = 2;
settings.values[kSettingsMaxHeaderListSize] = 5;
std::string data = EncodeSettings(settings);
QuicStreamFrame frame(receive_control_stream_->id(), false, 0,
QuicStringPiece(data));
QuicStreamFrame frame2(receive_control_stream_->id(), false, data.length(),
QuicStringPiece(data));
receive_control_stream_->OnStreamFrame(frame);
EXPECT_CALL(*connection_,
CloseConnection(QUIC_INVALID_STREAM_ID,
"Settings frames are received twice.", _));
receive_control_stream_->OnStreamFrame(frame2);
}
TEST_P(QuicReceiveControlStreamTest, ReceiveSettingsFragments) {
SettingsFrame settings;
settings.values[3] = 2;
settings.values[kSettingsMaxHeaderListSize] = 5;
std::string data = EncodeSettings(settings);
std::string data1 = data.substr(0, 1);
std::string data2 = data.substr(1, data.length() - 1);
QuicStreamFrame frame(receive_control_stream_->id(), false, 0,
QuicStringPiece(data.data(), 1));
QuicStreamFrame frame2(receive_control_stream_->id(), false, 1,
QuicStringPiece(data.data() + 1, data.length() - 1));
EXPECT_NE(5u, session_.max_outbound_header_list_size());
receive_control_stream_->OnStreamFrame(frame);
receive_control_stream_->OnStreamFrame(frame2);
EXPECT_EQ(5u, session_.max_outbound_header_list_size());
}
TEST_P(QuicReceiveControlStreamTest, ReceiveWrongFrame) {
GoAwayFrame goaway;
goaway.stream_id = 0x1;
HttpEncoder encoder;
std::unique_ptr<char[]> buffer;
QuicByteCount header_length = encoder.SerializeGoAwayFrame(goaway, &buffer);
std::string data = std::string(buffer.get(), header_length);
QuicStreamFrame frame(receive_control_stream_->id(), false, 0,
QuicStringPiece(data));
EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_DECODER_ERROR, _, _));
receive_control_stream_->OnStreamFrame(frame);
}
TEST_P(QuicReceiveControlStreamTest, PushPromiseOnControlStreamShouldClose) {
PushPromiseFrame push_promise;
push_promise.push_id = 0x01;
push_promise.headers = "Headers";
std::unique_ptr<char[]> buffer;
HttpEncoder encoder;
uint64_t length =
encoder.SerializePushPromiseFrameWithOnlyPushId(push_promise, &buffer);
QuicStreamFrame frame(receive_control_stream_->id(), false, 0, buffer.get(),
length);
// TODO(lassey) Check for HTTP_WRONG_STREAM error code.
EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_DECODER_ERROR, _, _))
.Times(AtLeast(1));
receive_control_stream_->OnStreamFrame(frame);
}
} // namespace
} // namespace test
} // namespace quic
<|endoftext|> |
<commit_before>/// \file urbi/ubinary.hh
// This file is part of UObject Component Architecture
// Copyright (c) 2007, 2008 Gostai S.A.S.
//
// Permission to use, copy, modify, and redistribute this software for
// non-commercial use is hereby granted.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// For more information, comments, bug reports: http://www.urbiforge.com
#ifndef URBI_UBINARY_HH
# define URBI_UBINARY_HH
# include <cstring>
# include <iosfwd>
# include <list>
# include <string>
# include <urbi/export.hh>
namespace urbi
{
/** Backward compatibility **/
enum USoundFormat
{
SOUND_RAW,
SOUND_WAV,
SOUND_MP3,
SOUND_OGG,
SOUND_UNKNOWN
};
enum USoundSampleFormat
{
SAMPLE_SIGNED=1,
SAMPLE_UNSIGNED=2
};
std::istream& operator>> (std::istream& is, USoundSampleFormat& f);
enum UImageFormat
{
IMAGE_RGB=1, ///< RGB 24 bit/pixel
IMAGE_YCbCr=2, ///< YCbCr 24 bit/pixel
IMAGE_JPEG=3, ///< JPEG
IMAGE_PPM=4, ///< RGB with a PPM header
IMAGE_UNKNOWN
};
enum UBinaryType
{
BINARY_NONE,
BINARY_UNKNOWN,
BINARY_IMAGE,
BINARY_SOUND
};
/*---------.
| USound. |
`---------*/
/** Class encapsulating sound information.
This class does not handle its memory: the data field msut be
freed manualy. */
class URBI_SDK_API USound
{
public:
char* data; ///< pointer to sound data
size_t size; ///< total size in byte
size_t channels; ///< number of audio channels
size_t rate; ///< rate in Hertz
size_t sampleSize; ///< sample size in bit
USoundFormat soundFormat; ///< format of the sound data
/// Return a legible definition of imageFormat.
const char* format_string () const;
enum SampleFormat
{
SAMPLE_SIGNED=1,
SAMPLE_UNSIGNED=2
};
USoundSampleFormat sampleFormat; ///< sample format
bool operator ==(const USound &b) const
{
return !memcmp(this, &b, sizeof(USound));
}
operator std::string() const;
};
/*---------.
| UImage. |
`---------*/
/** Class encapsulating an image.
This class does not handle its memory: the data field msut be
freed manualy. */
class URBI_SDK_API UImage
{
public:
/// Pointer to image data.
unsigned char* data;
/// Image size in byte.
size_t size;
/// Dimensions of the image.
size_t width, height;
UImageFormat imageFormat;
/// Return a legible definition of imageFormat.
const char* format_string() const;
};
/*--------------.
| UBinaryData. |
`--------------*/
//internal use: unparsed binary data
class URBI_SDK_API BinaryData
{
public:
BinaryData()
: data(0), size(0)
{}
BinaryData(void *d, size_t s)
: data(d), size(s)
{}
void* data;
size_t size;
};
/*----------.
| UBinary. |
`----------*/
/** Class containing binary data of known or unknown type.
Handles its memory: the data field will be freed when the destructor is called.
*/
class URBI_SDK_API UBinary
{
public:
UBinaryType type;
union
{
struct
{
void* data; ///< binary data
size_t size;
} common;
UImage image;
USound sound;
};
/// Extra bin headers(everything after BIN <size> and before ';'.
std::string message;
UBinary();
/// Deep copy constructor.
UBinary(const UBinary &b);
explicit UBinary(const UImage &);
explicit UBinary(const USound &);
/// Deep copy.
UBinary & operator = (const UBinary &b);
/// Build message from structures.
void buildMessage();
/// Get message extracted from structures.
std::string getMessage() const;
/// Frees binary buffer.
~UBinary();
/// Return true on success.
bool parse(std::istringstream& is,
const std::list<BinaryData>& bins,
std::list<BinaryData>::const_iterator& binpos);
int parse(const char* message, int pos,
const std::list<BinaryData>& bins,
std::list<BinaryData>::const_iterator& binpos);
/// Used by UValue::print for serialization.
std::ostream& print(std::ostream& o) const;
};
URBI_SDK_API
std::ostream& operator<< (std::ostream& o, const UBinary& t);
} // end namespace urbi
#endif // ! URBI_UBINARY_HH
<commit_msg>Add a SAMPLE_FLOAT type<commit_after>/// \file urbi/ubinary.hh
// This file is part of UObject Component Architecture
// Copyright (c) 2007, 2008 Gostai S.A.S.
//
// Permission to use, copy, modify, and redistribute this software for
// non-commercial use is hereby granted.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// For more information, comments, bug reports: http://www.urbiforge.com
#ifndef URBI_UBINARY_HH
# define URBI_UBINARY_HH
# include <cstring>
# include <iosfwd>
# include <list>
# include <string>
# include <urbi/export.hh>
namespace urbi
{
/** Backward compatibility **/
enum USoundFormat
{
SOUND_RAW,
SOUND_WAV,
SOUND_MP3,
SOUND_OGG,
SOUND_UNKNOWN
};
enum USoundSampleFormat
{
SAMPLE_SIGNED=1,
SAMPLE_UNSIGNED=2,
SAMPLE_FLOAT=3
};
std::istream& operator>> (std::istream& is, USoundSampleFormat& f);
enum UImageFormat
{
IMAGE_RGB=1, ///< RGB 24 bit/pixel
IMAGE_YCbCr=2, ///< YCbCr 24 bit/pixel
IMAGE_JPEG=3, ///< JPEG
IMAGE_PPM=4, ///< RGB with a PPM header
IMAGE_UNKNOWN
};
enum UBinaryType
{
BINARY_NONE,
BINARY_UNKNOWN,
BINARY_IMAGE,
BINARY_SOUND
};
/*---------.
| USound. |
`---------*/
/** Class encapsulating sound information.
This class does not handle its memory: the data field msut be
freed manualy. */
class URBI_SDK_API USound
{
public:
char* data; ///< pointer to sound data
size_t size; ///< total size in byte
size_t channels; ///< number of audio channels
size_t rate; ///< rate in Hertz
size_t sampleSize; ///< sample size in bit
USoundFormat soundFormat; ///< format of the sound data
/// Return a legible definition of imageFormat.
const char* format_string () const;
enum SampleFormat
{
SAMPLE_SIGNED=1,
SAMPLE_UNSIGNED=2
};
USoundSampleFormat sampleFormat; ///< sample format
bool operator ==(const USound &b) const
{
return !memcmp(this, &b, sizeof(USound));
}
operator std::string() const;
};
/*---------.
| UImage. |
`---------*/
/** Class encapsulating an image.
This class does not handle its memory: the data field msut be
freed manualy. */
class URBI_SDK_API UImage
{
public:
/// Pointer to image data.
unsigned char* data;
/// Image size in byte.
size_t size;
/// Dimensions of the image.
size_t width, height;
UImageFormat imageFormat;
/// Return a legible definition of imageFormat.
const char* format_string() const;
};
/*--------------.
| UBinaryData. |
`--------------*/
//internal use: unparsed binary data
class URBI_SDK_API BinaryData
{
public:
BinaryData()
: data(0), size(0)
{}
BinaryData(void *d, size_t s)
: data(d), size(s)
{}
void* data;
size_t size;
};
/*----------.
| UBinary. |
`----------*/
/** Class containing binary data of known or unknown type.
Handles its memory: the data field will be freed when the destructor is called.
*/
class URBI_SDK_API UBinary
{
public:
UBinaryType type;
union
{
struct
{
void* data; ///< binary data
size_t size;
} common;
UImage image;
USound sound;
};
/// Extra bin headers(everything after BIN <size> and before ';'.
std::string message;
UBinary();
/// Deep copy constructor.
UBinary(const UBinary &b);
explicit UBinary(const UImage &);
explicit UBinary(const USound &);
/// Deep copy.
UBinary & operator = (const UBinary &b);
/// Build message from structures.
void buildMessage();
/// Get message extracted from structures.
std::string getMessage() const;
/// Frees binary buffer.
~UBinary();
/// Return true on success.
bool parse(std::istringstream& is,
const std::list<BinaryData>& bins,
std::list<BinaryData>::const_iterator& binpos);
int parse(const char* message, int pos,
const std::list<BinaryData>& bins,
std::list<BinaryData>::const_iterator& binpos);
/// Used by UValue::print for serialization.
std::ostream& print(std::ostream& o) const;
};
URBI_SDK_API
std::ostream& operator<< (std::ostream& o, const UBinary& t);
} // end namespace urbi
#endif // ! URBI_UBINARY_HH
<|endoftext|> |
<commit_before>#include "Scene.h"
#include "../../OpenGLESApp2/OpenGLESApp2.Android.NativeActivity/Renderer.h"
namespace SunnySideUp {
using namespace Mai;
class TitleScene : public Scene {
public:
TitleScene()
: loaded(false)
, updateFunc(&TitleScene::DoFadeIn)
{}
virtual ~TitleScene() {}
virtual bool Load(Engine& engine) {
if (!loaded) {
objList.reserve(8);
Renderer& r = engine.GetRenderer();
{
auto obj = r.CreateObject("TitleLogo", Material(Color4B(255, 255, 255, 255), 0, 0), "default");
obj->SetTranslation(Vector3F(1.125f, 4.5f, -2.5f));
obj->SetRotation(degreeToRadian<float>(140), degreeToRadian<float>(0), degreeToRadian<float>(0));
//obj->SetScale(Vector3F(5, 5, 5));
objList.push_back(obj);
}
{
auto obj = r.CreateObject("ChickenEgg", Material(Color4B(255, 255, 255, 255), 0, 0), "default");
obj->SetAnimation(r.GetAnimation("Wait0"));
obj->SetTranslation(Vector3F(2.0f, 5, -6.1f));
obj->SetRotation(degreeToRadian<float>(30), degreeToRadian<float>(-30), degreeToRadian<float>(-15));
objList.push_back(obj);
}
{
auto obj = r.CreateObject("FlyingRock", Material(Color4B(255, 255, 255, 255), 0, 0), "default");
obj->SetTranslation(Vector3F(-4.5f, -5.5, -14));
obj->SetScale(Vector3F(3, 3, 3));
obj->SetRotation(degreeToRadian<float>(35), degreeToRadian<float>(-20), degreeToRadian<float>(0));
objList.push_back(obj);
}
{
auto obj = r.CreateObject("cloud0", Material(Color4B(255, 240, 250, 128), 0, 0), "cloud");
obj->SetTranslation(Vector3F(30, 0, -75));
obj->SetRotation(degreeToRadian<float>(90), degreeToRadian<float>(0), degreeToRadian<float>(0));
objList.push_back(obj);
}
animeNo = 0;
scaleTick = 0;
cloudRot = 0;
loaded = true;
}
status = STATUSCODE_RUNNABLE;
return true;
}
virtual bool Unload(Engine&) {
if (loaded) {
objList.clear();
loaded = false;
}
status = STATUSCODE_STOPPED;
return true;
}
virtual int Update(Engine& engine, float tick) {
for (auto e : objList) {
e->Update(tick);
}
Renderer& r = engine.GetRenderer();
r.Update(tick, Position3F(0, 0, 0), Vector3F(0.25f, 1, -1), Vector3F(0, 0, 1));
return (this->*updateFunc)(engine, tick);
}
/** Do fade in.
Transition to DoUpdate() when the fadein finished.
This is the update function called from Update().
*/
int DoFadeIn(Engine& engine, float) {
if (engine.IsInitialized()) {
Renderer& r = engine.GetRenderer();
r.SetFilterColor(Color4B(0, 0, 0, 255));
r.FadeIn(1.0f);
AudioInterface& audio = engine.GetAudio();
audio.PlayBGM("Audio/background.mp3");
updateFunc = &TitleScene::DoUpdate;
}
return SCENEID_CONTINUE;
}
/** Wait user input.
Transition to DoFadeOut() when receive user input.
This is the update function called from Update().
*/
int DoUpdate(Engine& engine, float tick) {
scaleTick += tick;
if (scaleTick > 2.0f) {
scaleTick -= 2.0f;
}
cloudRot += tick;
if (cloudRot > 360.0f) {
cloudRot -= 360.0f;
}
objList[3]->SetRotation(degreeToRadian<float>(90), degreeToRadian<float>(cloudRot), degreeToRadian<float>(0));
return SCENEID_CONTINUE;
}
/** Do fade out.
Transition to the scene of the start event when the fadeout finished.
This is the update function called from Update().
*/
int DoFadeOut(Engine& engine, float) {
Renderer& r = engine.GetRenderer();
if (r.GetCurrentFilterMode() == Renderer::FILTERMODE_NONE) {
r.FadeIn(1.0f);
engine.GetAudio().StopBGM();
return SCENEID_STARTEVENT;
}
return SCENEID_CONTINUE;
}
virtual void ProcessWindowEvent(Engine& engine, const Event& e) {
Renderer& r = engine.GetRenderer();
if (r.GetCurrentFilterMode() == Renderer::FILTERMODE_NONE) {
switch (e.Type) {
case Event::EVENT_MOUSE_BUTTON_PRESSED:
if (e.MouseButton.Button == MOUSEBUTTON_LEFT) {
r.FadeOut(Color4B(0, 0, 0, 0), 1.0f);
updateFunc = &TitleScene::DoFadeOut;
}
break;
case Event::EVENT_KEY_PRESSED: {
if (e.Key.Code == KEY_SPACE) {
static const char* const animeNameList[] = {
"Stand", "Wait0", "Wait1", "Walk", "Dive"
};
animeNo = (animeNo + 1) % 5;
objList[1]->SetAnimation(engine.GetRenderer().GetAnimation(animeNameList[animeNo]));
}
break;
}
default:
break;
}
}
}
virtual void Draw(Engine& engine) {
Renderer& r = engine.GetRenderer();
if (r.GetCurrentFilterMode() == Renderer::FILTERMODE_NONE) {
const char str[] = "TOUCH ME!";
float scale;
if (scaleTick < 1.0f) {
scale = 1.0f + scaleTick * 0.5f;
} else {
scale = 1.5f - (scaleTick - 1.0f) * 0.5f;
}
const float w = r.GetStringWidth(str) * scale;
r.AddString(0.5f - w * 0.5f, 0.7f, scale, Color4B(240, 240, 240, 255), str);
}
r.Render(&objList[0], &objList[0] + objList.size());
}
private:
std::vector<ObjectPtr> objList;
int animeNo;
bool loaded;
float scaleTick;
float cloudRot;
int (TitleScene::*updateFunc)(Engine&, float);
};
ScenePtr CreateTitleScene(Engine&) {
return ScenePtr(new TitleScene());
}
} // namespace SunnySideUp
<commit_msg>Change the allocation of the title objects.<commit_after>#include "Scene.h"
#include "../../OpenGLESApp2/OpenGLESApp2.Android.NativeActivity/Renderer.h"
namespace SunnySideUp {
using namespace Mai;
class TitleScene : public Scene {
public:
TitleScene()
: loaded(false)
, updateFunc(&TitleScene::DoFadeIn)
{}
virtual ~TitleScene() {}
virtual bool Load(Engine& engine) {
if (!loaded) {
eyePos = Position3F(8, 19.5f, 5);
eyeDir = Vector3F(-0.6f, 0.06f, -0.84f).Normalize();
objList.reserve(8);
Renderer& r = engine.GetRenderer();
boost::random::mt19937 random(static_cast<uint32_t>(time(nullptr)));
r.SetTimeOfScene(static_cast<TimeOfScene>(TimeOfScene_Noon + random() % 3));
{
auto obj = r.CreateObject("TitleLogo", Material(Color4B(255, 255, 255, 255), 0, 0), "default");
obj->SetTranslation(Vector3F(5.1f, 21.2f, 1.0f));
obj->SetRotation(degreeToRadian<float>(103), degreeToRadian<float>(2), degreeToRadian<float>(-46));
//obj->SetScale(Vector3F(5, 5, 5));
objList.push_back(obj);
}
{
auto obj = r.CreateObject("ChickenEgg", Material(Color4B(255, 255, 255, 255), 0, 0), "default");
obj->SetAnimation(r.GetAnimation("Wait0"));
obj->SetTranslation(Vector3F(3.9f, 19.25f, -2));
obj->SetRotation(degreeToRadian<float>(-6), degreeToRadian<float>(11), degreeToRadian<float>(1));
objList.push_back(obj);
}
{
auto obj = r.CreateObject("FlyingRock", Material(Color4B(255, 255, 255, 255), 0, 0), "default");
obj->SetTranslation(Vector3F(1.5f, 6, 2));
obj->SetScale(Vector3F(3, 3, 3));
obj->SetRotation(degreeToRadian<float>(-5), degreeToRadian<float>(22), degreeToRadian<float>(14));
objList.push_back(obj);
}
{
auto obj = r.CreateObject("cloud0", Material(Color4B(255, 240, 250, 128), 0, 0), "cloud");
obj->SetTranslation(Vector3F(30, 0, -75));
//obj->SetRotation(degreeToRadian<float>(90), degreeToRadian<float>(0), degreeToRadian<float>(0));
objList.push_back(obj);
}
animeNo = 0;
scaleTick = 0;
cloudRot = 0;
loaded = true;
}
status = STATUSCODE_RUNNABLE;
return true;
}
virtual bool Unload(Engine&) {
if (loaded) {
objList.clear();
loaded = false;
}
status = STATUSCODE_STOPPED;
return true;
}
virtual int Update(Engine& engine, float tick) {
for (auto e : objList) {
e->Update(tick);
}
Renderer& r = engine.GetRenderer();
r.Update(tick, eyePos, eyeDir, Vector3F(0, 1, 0));
return (this->*updateFunc)(engine, tick);
}
/** Do fade in.
Transition to DoUpdate() when the fadein finished.
This is the update function called from Update().
*/
int DoFadeIn(Engine& engine, float) {
if (engine.IsInitialized()) {
Renderer& r = engine.GetRenderer();
r.SetFilterColor(Color4B(0, 0, 0, 255));
r.FadeIn(1.0f);
AudioInterface& audio = engine.GetAudio();
audio.PlayBGM("Audio/background.mp3");
updateFunc = &TitleScene::DoUpdate;
}
return SCENEID_CONTINUE;
}
/** Wait user input.
Transition to DoFadeOut() when receive user input.
This is the update function called from Update().
*/
int DoUpdate(Engine& engine, float tick) {
scaleTick += tick;
if (scaleTick > 2.0f) {
scaleTick -= 2.0f;
}
cloudRot += tick;
if (cloudRot > 360.0f) {
cloudRot -= 360.0f;
}
objList[3]->SetRotation(degreeToRadian<float>(90), degreeToRadian<float>(cloudRot), degreeToRadian<float>(0));
return SCENEID_CONTINUE;
}
/** Do fade out.
Transition to the scene of the start event when the fadeout finished.
This is the update function called from Update().
*/
int DoFadeOut(Engine& engine, float) {
Renderer& r = engine.GetRenderer();
if (r.GetCurrentFilterMode() == Renderer::FILTERMODE_NONE) {
r.FadeIn(1.0f);
engine.GetAudio().StopBGM();
return SCENEID_STARTEVENT;
}
return SCENEID_CONTINUE;
}
virtual void ProcessWindowEvent(Engine& engine, const Event& e) {
Renderer& r = engine.GetRenderer();
if (r.GetCurrentFilterMode() == Renderer::FILTERMODE_NONE) {
switch (e.Type) {
case Event::EVENT_MOUSE_BUTTON_PRESSED:
if (e.MouseButton.Button == MOUSEBUTTON_LEFT) {
r.FadeOut(Color4B(0, 0, 0, 0), 1.0f);
updateFunc = &TitleScene::DoFadeOut;
}
break;
#ifndef NDEBUG
case Event::EVENT_KEY_PRESSED:
switch (e.Key.Code) {
case KEY_A:
eyeDir = (Matrix4x4::RotationY(degreeToRadian(1.0f)) * eyeDir).ToVec3();
break;
case KEY_D:
eyeDir = (Matrix4x4::RotationY(degreeToRadian(-1.0f)) * eyeDir).ToVec3();
break;
case KEY_SPACE: {
static const char* const animeNameList[] = {
"Stand", "Wait0", "Wait1", "Walk", "Dive"
};
animeNo = (animeNo + 1) % 5;
objList[1]->SetAnimation(engine.GetRenderer().GetAnimation(animeNameList[animeNo]));
break;
}
}
break;
#endif // NDEBUG
default:
break;
}
}
}
virtual void Draw(Engine& engine) {
Renderer& r = engine.GetRenderer();
if (r.GetCurrentFilterMode() == Renderer::FILTERMODE_NONE) {
const char str[] = "TOUCH ME!";
float scale;
if (scaleTick < 1.0f) {
scale = 1.0f + scaleTick * 0.5f;
} else {
scale = 1.5f - (scaleTick - 1.0f) * 0.5f;
}
const float w = r.GetStringWidth(str) * scale;
r.AddString(0.5f - w * 0.5f, 0.7f, scale, Color4B(240, 240, 240, 255), str);
}
r.Render(&objList[0], &objList[0] + objList.size());
}
private:
std::vector<ObjectPtr> objList;
Position3F eyePos;
Vector3F eyeDir;
int animeNo;
bool loaded;
float scaleTick;
float cloudRot;
int (TitleScene::*updateFunc)(Engine&, float);
};
ScenePtr CreateTitleScene(Engine&) {
return ScenePtr(new TitleScene());
}
} // namespace SunnySideUp
<|endoftext|> |
<commit_before>#pragma once
#include <stdexcept>
namespace estd
{
inline void throw_assert(bool condition, std::exception e = std::logic_error("throw_assert"))
{
if (!condition)
throw e;
}
inline void throw_assert(bool condition, std::string s)
{
if (!condition)
throw std::logic_error(s);
}
template<class T>
class mutref
{
public:
explicit mutref(T & obj)
: me(obj)
{
}
operator T&()
{
return me;
}
T* operator->()
{
return &me;
}
private:
T& me;
};
template<class T>
mutref<T> mut(T &obj) { return mutref<T>(obj); }
} // namespace estd
<commit_msg>A few fixes for estd::mutref<commit_after>#pragma once
#include <stdexcept>
namespace estd
{
inline void throw_assert(bool condition, std::exception e = std::logic_error("throw_assert"))
{
if (!condition)
throw e;
}
inline void throw_assert(bool condition, std::string s)
{
if (!condition)
throw std::logic_error(s);
}
template<class T>
class mutref
{
public:
explicit mutref(T & obj)
: me(obj)
{
}
template<class U, typename = std::is_base_of<U, T>>
operator mutref<U>()
{
return mutref<U>(me);
}
T& operator*()
{
return me;
}
operator T&()
{
return me;
}
T* operator->()
{
return &me;
}
private:
T& me;
};
template<class T>
mutref<T> mut(T &obj) { return mutref<T>(obj); }
} // namespace estd
<|endoftext|> |
<commit_before>/*
Copyright (c) 2017 Fatih Kaya
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#include <map>
#include <vector>
#include <string>
#include "roaring.hh"
#ifndef JILL_FIELD_HEADER_INCLUDED
#define JILL_FIELD_HEADER_INCLUDED
namespace jill {
namespace table {
class FieldBase {};
enum FieldType {
TIMESTAMP,
DIMENSION,
BOOL,
METRIC_INT,
METRIC_FLOAT
};
template <FieldType, typename T>
class Field : FieldBase {
private:
// name of the field
std::string name_;
// vector of values stored in the field
std::vector<T> vals;
// multi value fields(ex: tags)
std::vector< std::vector<T> > mvals;
// dimensions(ex: gender, country etc...)
std::map<T, Roaring *> dict_;
// true/false store
Roaring *roar_;
// element count that stored in this field
int count_;
// type of the this field
FieldType type_;
public:
// public methods
Field(std::string name);
std::string &name() {
return name_;
}
// add new data to the field
void insert(T &val);
// DIMENSION methods
std::map<std::string, Roaring *> &dict();
// BOOL methods
// get roaring bitmap of the field
Roaring *roar() {
if (type_ != BOOL)
throw std::runtime_error("can not get roaring bitmap of the non-bool fields");
return roar_;
}
};
} // namespace table
} // namespace jill
#endif
<commit_msg>add applyFilter's definition<commit_after>/*
Copyright (c) 2017 Fatih Kaya
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#include <map>
#include <vector>
#include <string>
#include "roaring.hh"
#include "query.h"
#ifndef JILL_FIELD_HEADER_INCLUDED
#define JILL_FIELD_HEADER_INCLUDED
namespace jill {
namespace table {
class FieldBase {};
enum FieldType {
TIMESTAMP,
DIMENSION,
BOOL,
METRIC_INT,
METRIC_FLOAT
};
template <FieldType, typename T>
class Field : FieldBase {
private:
// name of the field
std::string name_;
// vector of values stored in the field
std::vector<T> vals;
// multi value fields(ex: tags)
std::vector< std::vector<T> > mvals;
// dimensions(ex: gender, country etc...)
std::map<T, Roaring *> dict_;
// true/false store
Roaring *roar_;
// element count that stored in this field
int count_;
// type of the this field
FieldType type_;
public:
// public methods
Field(std::string name);
std::string &name() {
return name_;
}
// add new data to the field
void insert(T &val);
// DIMENSION methods
std::map<std::string, Roaring *> &dict();
// BOOL methods
// get roaring bitmap of the field
Roaring *roar() {
if (type_ != BOOL)
throw std::runtime_error("can not get roaring bitmap of the non-bool fields");
return roar_;
}
/////////////////////////
////// querying
/////////////////////////
Roaring *applyFilter(Filter *filter);
};
} // namespace table
} // namespace jill
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <boost/scoped_ptr.hpp>
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _MODE_T_
typedef int mode_t;
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#include "libtorrent/assert.hpp"
namespace
{
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
TORRENT_ASSERT(false);
return 0;
}
#ifdef WIN32
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
std::string const& utf8_native(std::string const& s)
{
return s;
}
#endif
}
namespace libtorrent
{
namespace fs = boost::filesystem;
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(1);
const file::seek_mode file::end(2);
struct file::impl
{
impl()
: m_fd(-1)
, m_open_mode(0)
{}
impl(fs::path const& path, int mode, error_code& ec)
: m_fd(-1)
, m_open_mode(0)
{
open(path, mode, ec);
}
~impl()
{
close();
}
bool open(fs::path const& path, int mode, error_code& ec)
{
close();
#ifdef TORRENT_WINDOWS
const int permissions = _S_IREAD | _S_IWRITE;
#ifdef defined UNICODE
#define open _wopen
std::wstring file_path(safe_convert(path.native_file_string()));
#else
#define open _open
std::string const& file_path = path.native_file_string();
#endif
#else // if not windows
const mode_t permissions = S_IRWXU | S_IRGRP | S_IROTH;
std::string const& file_path = path.native_file_string();
#endif
m_fd = ::open(file_path.c_str(), map_open_mode(mode), permissions);
#ifdef TORRENT_WINDOWS
#undef open
#endif
if (m_fd == -1)
{
ec = error_code(errno, get_posix_category());
return false;
}
m_open_mode = mode;
return true;
}
void close()
{
if (m_fd == -1) return;
#ifdef _WIN32
::_close(m_fd);
#else
::close(m_fd);
#endif
m_fd = -1;
m_open_mode = 0;
}
size_type read(char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT(m_open_mode & mode_in);
TORRENT_ASSERT(m_fd != -1);
#ifdef _WIN32
size_type ret = ::_read(m_fd, buf, num_bytes);
#else
size_type ret = ::read(m_fd, buf, num_bytes);
#endif
if (ret == -1) ec = error_code(errno, get_posix_category());
return ret;
}
size_type write(const char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT(m_open_mode & mode_out);
TORRENT_ASSERT(m_fd != -1);
// TODO: Test this a bit more, what happens with random failures in
// the files?
// if ((rand() % 100) > 80)
// throw file_error("debug");
#ifdef _WIN32
size_type ret = ::_write(m_fd, buf, num_bytes);
#else
size_type ret = ::write(m_fd, buf, num_bytes);
#endif
if (ret == -1) ec = error_code(errno, get_posix_category());
return ret;
}
bool set_size(size_type s, error_code& ec)
{
#ifdef _WIN32
#error file.cpp is for posix systems only. use file_win.cpp on windows
#else
if (ftruncate(m_fd, s) < 0)
{
ec = error_code(errno, get_posix_category());
return false;
}
return true;
#endif
}
size_type seek(size_type offset, int m, error_code& ec)
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
size_type ret = lseek(m_fd, offset, seekdir);
#endif
// For some strange reason this fails
// on win32. Use windows specific file
// wrapper instead.
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
}
size_type tell(error_code& ec)
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
size_type ret;
#ifdef _WIN32
ret = _telli64(m_fd);
#else
ret = lseek(m_fd, 0, SEEK_CUR);
#endif
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
}
int m_fd;
int m_open_mode;
};
// pimpl forwardings
file::file() : m_impl(new impl()) {}
file::file(fs::path const& p, file::open_mode m, error_code& ec)
: m_impl(new impl(p, m.m_mask, ec))
{}
file::~file() {}
bool file::open(fs::path const& p, file::open_mode m, error_code& ec)
{
return m_impl->open(p, m.m_mask, ec);
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buf, size_type num_bytes, error_code& ec)
{
return m_impl->write(buf, num_bytes, ec);
}
size_type file::read(char* buf, size_type num_bytes, error_code& ec)
{
return m_impl->read(buf, num_bytes, ec);
}
bool file::set_size(size_type s, error_code& ec)
{
return m_impl->set_size(s, ec);
}
size_type file::seek(size_type pos, file::seek_mode m, error_code& ec)
{
return m_impl->seek(pos, m.m_val, ec);
}
size_type file::tell(error_code& ec)
{
return m_impl->tell(ec);
}
}
<commit_msg>set all permission bits on files and let umask handle reducing permissions<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <boost/scoped_ptr.hpp>
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _MODE_T_
typedef int mode_t;
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#include "libtorrent/assert.hpp"
namespace
{
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
TORRENT_ASSERT(false);
return 0;
}
#ifdef WIN32
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
std::string const& utf8_native(std::string const& s)
{
return s;
}
#endif
}
namespace libtorrent
{
namespace fs = boost::filesystem;
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(1);
const file::seek_mode file::end(2);
struct file::impl
{
impl()
: m_fd(-1)
, m_open_mode(0)
{}
impl(fs::path const& path, int mode, error_code& ec)
: m_fd(-1)
, m_open_mode(0)
{
open(path, mode, ec);
}
~impl()
{
close();
}
bool open(fs::path const& path, int mode, error_code& ec)
{
close();
#ifdef TORRENT_WINDOWS
const int permissions = _S_IREAD | _S_IWRITE;
#ifdef defined UNICODE
#define open _wopen
std::wstring file_path(safe_convert(path.native_file_string()));
#else
#define open _open
std::string const& file_path = path.native_file_string();
#endif
#else // if not windows
// rely on default umask to filter x and w permissions
// for group and others
const mode_t permissions = S_IRWXU | S_IRWXG | S_IRWXO;
std::string const& file_path = path.native_file_string();
#endif
m_fd = ::open(file_path.c_str(), map_open_mode(mode), permissions);
#ifdef TORRENT_WINDOWS
#undef open
#endif
if (m_fd == -1)
{
ec = error_code(errno, get_posix_category());
return false;
}
m_open_mode = mode;
return true;
}
void close()
{
if (m_fd == -1) return;
#ifdef _WIN32
::_close(m_fd);
#else
::close(m_fd);
#endif
m_fd = -1;
m_open_mode = 0;
}
size_type read(char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT(m_open_mode & mode_in);
TORRENT_ASSERT(m_fd != -1);
#ifdef _WIN32
size_type ret = ::_read(m_fd, buf, num_bytes);
#else
size_type ret = ::read(m_fd, buf, num_bytes);
#endif
if (ret == -1) ec = error_code(errno, get_posix_category());
return ret;
}
size_type write(const char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT(m_open_mode & mode_out);
TORRENT_ASSERT(m_fd != -1);
// TODO: Test this a bit more, what happens with random failures in
// the files?
// if ((rand() % 100) > 80)
// throw file_error("debug");
#ifdef _WIN32
size_type ret = ::_write(m_fd, buf, num_bytes);
#else
size_type ret = ::write(m_fd, buf, num_bytes);
#endif
if (ret == -1) ec = error_code(errno, get_posix_category());
return ret;
}
bool set_size(size_type s, error_code& ec)
{
#ifdef _WIN32
#error file.cpp is for posix systems only. use file_win.cpp on windows
#else
if (ftruncate(m_fd, s) < 0)
{
ec = error_code(errno, get_posix_category());
return false;
}
return true;
#endif
}
size_type seek(size_type offset, int m, error_code& ec)
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
size_type ret = lseek(m_fd, offset, seekdir);
#endif
// For some strange reason this fails
// on win32. Use windows specific file
// wrapper instead.
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
}
size_type tell(error_code& ec)
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
size_type ret;
#ifdef _WIN32
ret = _telli64(m_fd);
#else
ret = lseek(m_fd, 0, SEEK_CUR);
#endif
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
}
int m_fd;
int m_open_mode;
};
// pimpl forwardings
file::file() : m_impl(new impl()) {}
file::file(fs::path const& p, file::open_mode m, error_code& ec)
: m_impl(new impl(p, m.m_mask, ec))
{}
file::~file() {}
bool file::open(fs::path const& p, file::open_mode m, error_code& ec)
{
return m_impl->open(p, m.m_mask, ec);
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buf, size_type num_bytes, error_code& ec)
{
return m_impl->write(buf, num_bytes, ec);
}
size_type file::read(char* buf, size_type num_bytes, error_code& ec)
{
return m_impl->read(buf, num_bytes, ec);
}
bool file::set_size(size_type s, error_code& ec)
{
return m_impl->set_size(s, ec);
}
size_type file::seek(size_type pos, file::seek_mode m, error_code& ec)
{
return m_impl->seek(pos, m.m_val, ec);
}
size_type file::tell(error_code& ec)
{
return m_impl->tell(ec);
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <boost/scoped_ptr.hpp>
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _MODE_T_
typedef int mode_t;
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#include "libtorrent/assert.hpp"
namespace
{
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
TORRENT_ASSERT(false);
return 0;
}
#ifdef WIN32
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
std::string utf8_native(std::string const& s)
{
return s;
}
#endif
}
namespace libtorrent
{
namespace fs = boost::filesystem;
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(1);
const file::seek_mode file::end(2);
struct file::impl
{
impl()
: m_fd(-1)
, m_open_mode(0)
{}
impl(fs::path const& path, int mode)
: m_fd(-1)
, m_open_mode(0)
{
open(path, mode);
}
~impl()
{
close();
}
bool open(fs::path const& path, int mode)
{
close();
#if defined(_WIN32) && defined(UNICODE)
std::wstring wpath(safe_convert(path.native_file_string()));
m_fd = ::_wopen(
wpath.c_str()
, map_open_mode(mode)
, S_IREAD | S_IWRITE);
#else
#ifdef _WIN32
m_fd = ::_open(
#else
m_fd = ::open(
#endif
utf8_native(path.native_file_string()).c_str()
, map_open_mode(mode)
#ifdef _WIN32
, S_IREAD | S_IWRITE);
#else
, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
#endif
#endif
if (m_fd == -1)
{
std::stringstream msg;
msg << "open failed: '" << path.native_file_string() << "'. "
<< std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
return false;
}
m_open_mode = mode;
return true;
}
void close()
{
if (m_fd == -1) return;
#ifdef _WIN32
::_close(m_fd);
#else
::close(m_fd);
#endif
m_fd = -1;
m_open_mode = 0;
}
size_type read(char* buf, size_type num_bytes)
{
TORRENT_ASSERT(m_open_mode & mode_in);
TORRENT_ASSERT(m_fd != -1);
#ifdef _WIN32
size_type ret = ::_read(m_fd, buf, num_bytes);
#else
size_type ret = ::read(m_fd, buf, num_bytes);
#endif
if (ret == -1)
{
std::stringstream msg;
msg << "read failed: " << std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
}
return ret;
}
size_type write(const char* buf, size_type num_bytes)
{
TORRENT_ASSERT(m_open_mode & mode_out);
TORRENT_ASSERT(m_fd != -1);
// TODO: Test this a bit more, what happens with random failures in
// the files?
// if ((rand() % 100) > 80)
// throw file_error("debug");
#ifdef _WIN32
size_type ret = ::_write(m_fd, buf, num_bytes);
#else
size_type ret = ::write(m_fd, buf, num_bytes);
#endif
if (ret == -1)
{
std::stringstream msg;
msg << "write failed: " << std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
}
return ret;
}
bool set_size(size_type s)
{
#ifdef _WIN32
#error file.cpp is for posix systems only. use file_win.cpp on windows
#else
if (ftruncate(m_fd, s) < 0)
{
std::stringstream msg;
msg << "ftruncate failed: '" << std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
return false;
}
return true;
#endif
}
size_type seek(size_type offset, int m = 1)
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
size_type ret = lseek(m_fd, offset, seekdir);
#endif
// For some strange reason this fails
// on win32. Use windows specific file
// wrapper instead.
if (ret == -1)
{
std::stringstream msg;
msg << "seek failed: '" << std::strerror(errno)
<< "' fd: " << m_fd
<< " offset: " << offset
<< " seekdir: " << seekdir;
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
return -1;
}
return ret;
}
size_type tell()
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
#ifdef _WIN32
return _telli64(m_fd);
#else
return lseek(m_fd, 0, SEEK_CUR);
#endif
}
std::string const& error() const
{
if (!m_error) m_error.reset(new std::string);
return *m_error;
}
int m_fd;
int m_open_mode;
mutable boost::scoped_ptr<std::string> m_error;
};
// pimpl forwardings
file::file() : m_impl(new impl()) {}
file::file(fs::path const& p, file::open_mode m)
: m_impl(new impl(p, m.m_mask))
{}
file::~file() {}
bool file::open(fs::path const& p, file::open_mode m)
{
return m_impl->open(p, m.m_mask);
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buf, size_type num_bytes)
{
return m_impl->write(buf, num_bytes);
}
size_type file::read(char* buf, size_type num_bytes)
{
return m_impl->read(buf, num_bytes);
}
bool file::set_size(size_type s)
{
return m_impl->set_size(s);
}
size_type file::seek(size_type pos, file::seek_mode m)
{
return m_impl->seek(pos, m.m_val);
}
size_type file::tell()
{
return m_impl->tell();
}
std::string const& file::error() const
{
return m_impl->error();
}
}
<commit_msg>removed hard coded file permission bits<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <boost/scoped_ptr.hpp>
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _MODE_T_
typedef int mode_t;
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#include "libtorrent/assert.hpp"
namespace
{
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
TORRENT_ASSERT(false);
return 0;
}
#ifdef WIN32
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
std::string utf8_native(std::string const& s)
{
return s;
}
#endif
}
namespace libtorrent
{
namespace fs = boost::filesystem;
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(1);
const file::seek_mode file::end(2);
struct file::impl
{
impl()
: m_fd(-1)
, m_open_mode(0)
{}
impl(fs::path const& path, int mode)
: m_fd(-1)
, m_open_mode(0)
{
open(path, mode);
}
~impl()
{
close();
}
bool open(fs::path const& path, int mode)
{
close();
#if defined _WIN32 && defined UNICODE
std::wstring wpath(safe_convert(path.native_file_string()));
m_fd = ::_wopen(
wpath.c_str()
, map_open_mode(mode));
#elif defined _WIN32
m_fd = ::_open(
utf8_native(path.native_file_string()).c_str()
, map_open_mode(mode));
#else
m_fd = ::open(
utf8_native(path.native_file_string()).c_str()
, map_open_mode(mode));
#endif
if (m_fd == -1)
{
std::stringstream msg;
msg << "open failed: '" << path.native_file_string() << "'. "
<< std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
return false;
}
m_open_mode = mode;
return true;
}
void close()
{
if (m_fd == -1) return;
#ifdef _WIN32
::_close(m_fd);
#else
::close(m_fd);
#endif
m_fd = -1;
m_open_mode = 0;
}
size_type read(char* buf, size_type num_bytes)
{
TORRENT_ASSERT(m_open_mode & mode_in);
TORRENT_ASSERT(m_fd != -1);
#ifdef _WIN32
size_type ret = ::_read(m_fd, buf, num_bytes);
#else
size_type ret = ::read(m_fd, buf, num_bytes);
#endif
if (ret == -1)
{
std::stringstream msg;
msg << "read failed: " << std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
}
return ret;
}
size_type write(const char* buf, size_type num_bytes)
{
TORRENT_ASSERT(m_open_mode & mode_out);
TORRENT_ASSERT(m_fd != -1);
// TODO: Test this a bit more, what happens with random failures in
// the files?
// if ((rand() % 100) > 80)
// throw file_error("debug");
#ifdef _WIN32
size_type ret = ::_write(m_fd, buf, num_bytes);
#else
size_type ret = ::write(m_fd, buf, num_bytes);
#endif
if (ret == -1)
{
std::stringstream msg;
msg << "write failed: " << std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
}
return ret;
}
bool set_size(size_type s)
{
#ifdef _WIN32
#error file.cpp is for posix systems only. use file_win.cpp on windows
#else
if (ftruncate(m_fd, s) < 0)
{
std::stringstream msg;
msg << "ftruncate failed: '" << std::strerror(errno);
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
return false;
}
return true;
#endif
}
size_type seek(size_type offset, int m = 1)
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
size_type ret = lseek(m_fd, offset, seekdir);
#endif
// For some strange reason this fails
// on win32. Use windows specific file
// wrapper instead.
if (ret == -1)
{
std::stringstream msg;
msg << "seek failed: '" << std::strerror(errno)
<< "' fd: " << m_fd
<< " offset: " << offset
<< " seekdir: " << seekdir;
if (!m_error) m_error.reset(new std::string);
*m_error = msg.str();
return -1;
}
return ret;
}
size_type tell()
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
#ifdef _WIN32
return _telli64(m_fd);
#else
return lseek(m_fd, 0, SEEK_CUR);
#endif
}
std::string const& error() const
{
if (!m_error) m_error.reset(new std::string);
return *m_error;
}
int m_fd;
int m_open_mode;
mutable boost::scoped_ptr<std::string> m_error;
};
// pimpl forwardings
file::file() : m_impl(new impl()) {}
file::file(fs::path const& p, file::open_mode m)
: m_impl(new impl(p, m.m_mask))
{}
file::~file() {}
bool file::open(fs::path const& p, file::open_mode m)
{
return m_impl->open(p, m.m_mask);
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buf, size_type num_bytes)
{
return m_impl->write(buf, num_bytes);
}
size_type file::read(char* buf, size_type num_bytes)
{
return m_impl->read(buf, num_bytes);
}
bool file::set_size(size_type s)
{
return m_impl->set_size(s);
}
size_type file::seek(size_type pos, file::seek_mode m)
{
return m_impl->seek(pos, m.m_val);
}
size_type file::tell()
{
return m_impl->tell();
}
std::string const& file::error() const
{
return m_impl->error();
}
}
<|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 "content/browser/renderer_host/clipboard_message_filter.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/clipboard_dispatcher.h"
#include "chrome/common/clipboard_messages.h"
#include "googleurl/src/gurl.h"
#include "ipc/ipc_message_macros.h"
namespace {
// Completes a clipboard write initiated by the renderer. The write must be
// performed on the UI thread because the clipboard service from the IO thread
// cannot create windows so it cannot be the "owner" of the clipboard's
// contents.
class WriteClipboardTask : public Task {
public:
explicit WriteClipboardTask(ui::Clipboard::ObjectMap* objects)
: objects_(objects) {}
~WriteClipboardTask() {}
void Run() {
g_browser_process->clipboard()->WriteObjects(*objects_.get());
}
private:
scoped_ptr<ui::Clipboard::ObjectMap> objects_;
};
} // namespace
ClipboardMessageFilter::ClipboardMessageFilter() {
}
void ClipboardMessageFilter::OverrideThreadForMessage(
const IPC::Message& message, BrowserThread::ID* thread) {
#if defined(USE_X11)
if (message.type() == ViewHostMsg_ClipboardHostMsg_ReadImage::ID)
*thread = BrowserThread::BACKGROUND_X11;
else if (IPC_MESSAGE_CLASS(message) == ClipboardMsgStart)
*thread = BrowserThread::UI;
#endif
}
bool ClipboardMessageFilter::OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(ClipboardMessageFilter, message, *message_was_ok)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_WriteObjectsAsync, OnWriteObjectsAsync)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_WriteObjectsSync, OnWriteObjectsSync)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_IsFormatAvailable, OnIsFormatAvailable)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadText, OnReadText)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadAsciiText, OnReadAsciiText)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadHTML, OnReadHTML)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadImage, OnReadImage)
#if defined(OS_MACOSX)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_FindPboardWriteStringAsync,
OnFindPboardWriteString)
#endif
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadAvailableTypes,
OnReadAvailableTypes)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadData, OnReadData)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadFilenames, OnReadFilenames)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
ClipboardMessageFilter::~ClipboardMessageFilter() {
}
void ClipboardMessageFilter::OnWriteObjectsSync(
const ui::Clipboard::ObjectMap& objects,
base::SharedMemoryHandle bitmap_handle) {
DCHECK(base::SharedMemory::IsHandleValid(bitmap_handle))
<< "Bad bitmap handle";
// We cannot write directly from the IO thread, and cannot service the IPC
// on the UI thread. We'll copy the relevant data and get a handle to any
// shared memory so it doesn't go away when we resume the renderer, and post
// a task to perform the write on the UI thread.
ui::Clipboard::ObjectMap* long_living_objects =
new ui::Clipboard::ObjectMap(objects);
// Splice the shared memory handle into the clipboard data.
ui::Clipboard::ReplaceSharedMemHandle(long_living_objects, bitmap_handle,
peer_handle());
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
new WriteClipboardTask(long_living_objects));
}
void ClipboardMessageFilter::OnWriteObjectsAsync(
const ui::Clipboard::ObjectMap& objects) {
// We cannot write directly from the IO thread, and cannot service the IPC
// on the UI thread. We'll copy the relevant data and post a task to preform
// the write on the UI thread.
ui::Clipboard::ObjectMap* long_living_objects =
new ui::Clipboard::ObjectMap(objects);
// This async message doesn't support shared-memory based bitmaps; they must
// be removed otherwise we might dereference a rubbish pointer.
long_living_objects->erase(ui::Clipboard::CBF_SMBITMAP);
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
new WriteClipboardTask(long_living_objects));
}
void ClipboardMessageFilter::OnIsFormatAvailable(
ui::Clipboard::FormatType format, ui::Clipboard::Buffer buffer,
bool* result) {
*result = GetClipboard()->IsFormatAvailable(format, buffer);
}
void ClipboardMessageFilter::OnReadText(
ui::Clipboard::Buffer buffer, string16* result) {
GetClipboard()->ReadText(buffer, result);
}
void ClipboardMessageFilter::OnReadAsciiText(
ui::Clipboard::Buffer buffer, std::string* result) {
GetClipboard()->ReadAsciiText(buffer, result);
}
void ClipboardMessageFilter::OnReadHTML(
ui::Clipboard::Buffer buffer, string16* markup, GURL* url) {
std::string src_url_str;
GetClipboard()->ReadHTML(buffer, markup, &src_url_str);
*url = GURL(src_url_str);
}
void ClipboardMessageFilter::OnReadImage(
ui::Clipboard::Buffer buffer, std::string* data) {
GetClipboard()->ReadImage(buffer, data);
}
void ClipboardMessageFilter::OnReadAvailableTypes(
ui::Clipboard::Buffer buffer, bool* succeeded, std::vector<string16>* types,
bool* contains_filenames) {
*contains_filenames = false;
*succeeded = ClipboardDispatcher::ReadAvailableTypes(
buffer, types, contains_filenames);
}
void ClipboardMessageFilter::OnReadData(
ui::Clipboard::Buffer buffer, const string16& type, bool* succeeded,
string16* data, string16* metadata) {
*succeeded = ClipboardDispatcher::ReadData(buffer, type, data, metadata);
}
void ClipboardMessageFilter::OnReadFilenames(
ui::Clipboard::Buffer buffer, bool* succeeded,
std::vector<string16>* filenames) {
*succeeded = ClipboardDispatcher::ReadFilenames(buffer, filenames);
}
// static
ui::Clipboard* ClipboardMessageFilter::GetClipboard() {
// We have a static instance of the clipboard service for use by all message
// filters. This instance lives for the life of the browser processes.
static ui::Clipboard* clipboard = new ui::Clipboard;
return clipboard;
}
<commit_msg>Fix build break after r78134.<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 "content/browser/renderer_host/clipboard_message_filter.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/clipboard_dispatcher.h"
#include "chrome/common/clipboard_messages.h"
#include "googleurl/src/gurl.h"
#include "ipc/ipc_message_macros.h"
namespace {
// Completes a clipboard write initiated by the renderer. The write must be
// performed on the UI thread because the clipboard service from the IO thread
// cannot create windows so it cannot be the "owner" of the clipboard's
// contents.
class WriteClipboardTask : public Task {
public:
explicit WriteClipboardTask(ui::Clipboard::ObjectMap* objects)
: objects_(objects) {}
~WriteClipboardTask() {}
void Run() {
g_browser_process->clipboard()->WriteObjects(*objects_.get());
}
private:
scoped_ptr<ui::Clipboard::ObjectMap> objects_;
};
} // namespace
ClipboardMessageFilter::ClipboardMessageFilter() {
}
void ClipboardMessageFilter::OverrideThreadForMessage(
const IPC::Message& message, BrowserThread::ID* thread) {
#if defined(USE_X11)
if (message.type() == ClipboardHostMsg_ReadImage::ID)
*thread = BrowserThread::BACKGROUND_X11;
else if (IPC_MESSAGE_CLASS(message) == ClipboardMsgStart)
*thread = BrowserThread::UI;
#endif
}
bool ClipboardMessageFilter::OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(ClipboardMessageFilter, message, *message_was_ok)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_WriteObjectsAsync, OnWriteObjectsAsync)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_WriteObjectsSync, OnWriteObjectsSync)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_IsFormatAvailable, OnIsFormatAvailable)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadText, OnReadText)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadAsciiText, OnReadAsciiText)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadHTML, OnReadHTML)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadImage, OnReadImage)
#if defined(OS_MACOSX)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_FindPboardWriteStringAsync,
OnFindPboardWriteString)
#endif
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadAvailableTypes,
OnReadAvailableTypes)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadData, OnReadData)
IPC_MESSAGE_HANDLER(ClipboardHostMsg_ReadFilenames, OnReadFilenames)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
ClipboardMessageFilter::~ClipboardMessageFilter() {
}
void ClipboardMessageFilter::OnWriteObjectsSync(
const ui::Clipboard::ObjectMap& objects,
base::SharedMemoryHandle bitmap_handle) {
DCHECK(base::SharedMemory::IsHandleValid(bitmap_handle))
<< "Bad bitmap handle";
// We cannot write directly from the IO thread, and cannot service the IPC
// on the UI thread. We'll copy the relevant data and get a handle to any
// shared memory so it doesn't go away when we resume the renderer, and post
// a task to perform the write on the UI thread.
ui::Clipboard::ObjectMap* long_living_objects =
new ui::Clipboard::ObjectMap(objects);
// Splice the shared memory handle into the clipboard data.
ui::Clipboard::ReplaceSharedMemHandle(long_living_objects, bitmap_handle,
peer_handle());
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
new WriteClipboardTask(long_living_objects));
}
void ClipboardMessageFilter::OnWriteObjectsAsync(
const ui::Clipboard::ObjectMap& objects) {
// We cannot write directly from the IO thread, and cannot service the IPC
// on the UI thread. We'll copy the relevant data and post a task to preform
// the write on the UI thread.
ui::Clipboard::ObjectMap* long_living_objects =
new ui::Clipboard::ObjectMap(objects);
// This async message doesn't support shared-memory based bitmaps; they must
// be removed otherwise we might dereference a rubbish pointer.
long_living_objects->erase(ui::Clipboard::CBF_SMBITMAP);
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
new WriteClipboardTask(long_living_objects));
}
void ClipboardMessageFilter::OnIsFormatAvailable(
ui::Clipboard::FormatType format, ui::Clipboard::Buffer buffer,
bool* result) {
*result = GetClipboard()->IsFormatAvailable(format, buffer);
}
void ClipboardMessageFilter::OnReadText(
ui::Clipboard::Buffer buffer, string16* result) {
GetClipboard()->ReadText(buffer, result);
}
void ClipboardMessageFilter::OnReadAsciiText(
ui::Clipboard::Buffer buffer, std::string* result) {
GetClipboard()->ReadAsciiText(buffer, result);
}
void ClipboardMessageFilter::OnReadHTML(
ui::Clipboard::Buffer buffer, string16* markup, GURL* url) {
std::string src_url_str;
GetClipboard()->ReadHTML(buffer, markup, &src_url_str);
*url = GURL(src_url_str);
}
void ClipboardMessageFilter::OnReadImage(
ui::Clipboard::Buffer buffer, std::string* data) {
GetClipboard()->ReadImage(buffer, data);
}
void ClipboardMessageFilter::OnReadAvailableTypes(
ui::Clipboard::Buffer buffer, bool* succeeded, std::vector<string16>* types,
bool* contains_filenames) {
*contains_filenames = false;
*succeeded = ClipboardDispatcher::ReadAvailableTypes(
buffer, types, contains_filenames);
}
void ClipboardMessageFilter::OnReadData(
ui::Clipboard::Buffer buffer, const string16& type, bool* succeeded,
string16* data, string16* metadata) {
*succeeded = ClipboardDispatcher::ReadData(buffer, type, data, metadata);
}
void ClipboardMessageFilter::OnReadFilenames(
ui::Clipboard::Buffer buffer, bool* succeeded,
std::vector<string16>* filenames) {
*succeeded = ClipboardDispatcher::ReadFilenames(buffer, filenames);
}
// static
ui::Clipboard* ClipboardMessageFilter::GetClipboard() {
// We have a static instance of the clipboard service for use by all message
// filters. This instance lives for the life of the browser processes.
static ui::Clipboard* clipboard = new ui::Clipboard;
return clipboard;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Author:
* Jeremy Lainé
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include <QtCore/QCoreApplication>
#include "QXmppLogger.h"
#include "QXmppIncomingClient.h"
#include "QXmppServer.h"
#define USERNAME "qxmpp.test1"
#define PASSWORD "qxmpp123"
class passwordChecker : public QXmppPasswordChecker
{
/// Checks that the given credentials are valid.
bool check(const QString &username, const QString &password)
{
return (username == USERNAME && password == PASSWORD);
};
/// Retrieves the password for the given username.
bool get(const QString &username, QString &password)
{
if (username == USERNAME)
{
password = PASSWORD;
return true;
} else {
return false;
}
};
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// we want one argument : the domain to serve
if (argc != 2)
{
fprintf(stderr, "Usage: xmppServer <domain>\n");
return EXIT_FAILURE;
}
const QString domain = QString::fromLocal8Bit(argv[1]);
QXmppLogger logger;
logger.setLoggingType(QXmppLogger::StdoutLogging);
passwordChecker checker;
QXmppServer server;
server.setDomain(domain);
server.setLogger(&logger);
server.setPasswordChecker(&checker);
server.listenForClients();
server.listenForServers();
return a.exec();
}
<commit_msg>adapt to new API<commit_after>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Author:
* Jeremy Lainé
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include <QtCore/QCoreApplication>
#include "QXmppLogger.h"
#include "QXmppIncomingClient.h"
#include "QXmppServer.h"
#define USERNAME "qxmpp.test1"
#define PASSWORD "qxmpp123"
class passwordChecker : public QXmppPasswordChecker
{
/// Checks that the given credentials are valid.
bool checkCredentials(const QString &username, const QString &password)
{
return (username == USERNAME && password == PASSWORD);
};
/// Retrieves the password for the given username.
bool getPassword(const QString &username, QString &password)
{
if (username == USERNAME)
{
password = PASSWORD;
return true;
} else {
return false;
}
};
/// Returns true as we support retrieving a password.
bool hasPasswords() const
{
return true;
};
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// we want one argument : the domain to serve
if (argc != 2)
{
fprintf(stderr, "Usage: xmppServer <domain>\n");
return EXIT_FAILURE;
}
const QString domain = QString::fromLocal8Bit(argv[1]);
QXmppLogger logger;
logger.setLoggingType(QXmppLogger::StdoutLogging);
passwordChecker checker;
QXmppServer server;
server.setDomain(domain);
server.setLogger(&logger);
server.setPasswordChecker(&checker);
server.listenForClients();
server.listenForServers();
return a.exec();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: javaldx.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2004-07-23 11:49:55 $
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "osl/thread.h"
#include "sal/types.h"
#include "rtl/ustring.hxx"
#include "rtl/byteseq.hxx"
#include "jvmfwk/framework.h"
using namespace rtl;
#define OUSTR(x) OUString(RTL_CONSTASCII_USTRINGPARAM( x ))
static sal_Bool hasOption(char* szOption, int argc, char** argv);
static rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData);
//static sal_Bool printPaths(const OUString& sPathFile);
#define HELP_TEXT \
"\njavaldx is necessary to make Java work on some UNIX platforms." \
"It prints a string to std out that consists of directories which " \
"have to be included into the LD_LIBRARY_PATH variable.The setting of " \
"the variable usually occurs in a shell script that runs javaldx.\n" \
"The directories are from the chosen java installation. \n" \
"Options are: \n"\
"--help or -h\n"
int main(int argc, char **argv)
{
if( hasOption("--help",argc, argv) || hasOption("-h", argc, argv))
{
fprintf(stdout, HELP_TEXT);// default
return 0;
}
sal_Bool bEnabled = sal_False;
if (jfw_getEnabled( & bEnabled) != JFW_E_NONE)
{
fprintf(stderr,"javaldx failed! \n");
return -1;
}
if (bEnabled == sal_False)
{
//Do not do any preparation because that may only slow startup time.
return 0;
}
JavaInfo * pInfo = NULL;
javaFrameworkError errcode = JFW_E_NONE;
errcode = jfw_getSelectedJRE( & pInfo);
if (errcode == JFW_E_INVALID_SETTINGS)
{
fprintf(stderr,"javaldx failed. User must select a JRE from options dialog!");
return -1;
}
else if (errcode != JFW_E_NONE)
{
fprintf(stderr,"javaldx failed! \n");
return -1;
}
if (pInfo == NULL)
{
errcode = jfw_findAndSelectJRE( & pInfo);
if (errcode == JFW_E_NO_JAVA_FOUND)
{
fprintf(stderr,"javaldx: Could not find a Java Runtime Environment! \n");
return 0;
}
else if (errcode != JFW_E_NONE)
{
fprintf(stderr,"javaldx failed!\n");
return -1;
}
}
//Only do something if the sunjavaplugin created this JavaInfo
rtl::OUString sVendor1(RTL_CONSTASCII_USTRINGPARAM("Sun Microsystems Inc."));
rtl::OUString sVendor2(RTL_CONSTASCII_USTRINGPARAM("IBM Corporation"));
rtl::OUString sVendor3(RTL_CONSTASCII_USTRINGPARAM("Blackdown Java-Linux Team"));
rtl::OUString sVendor4(RTL_CONSTASCII_USTRINGPARAM("Apple Computer, Inc."));
if ( ! (sVendor1.equals(pInfo->sVendor) == sal_True
|| sVendor2.equals(pInfo->sVendor) == sal_True
|| sVendor3.equals(pInfo->sVendor) == sal_True
|| sVendor4.equals(pInfo->sVendor) == sal_True))
return 0;
rtl::OString sPaths = getLD_LIBRARY_PATH(pInfo->arVendorData);
fprintf(stdout, "%s\n", sPaths.getStr());
jfw_freeJavaInfo(pInfo);
return 0;
}
rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData)
{
const sal_Unicode* chars = (sal_Unicode*) vendorData.getConstArray();
sal_Int32 len = vendorData.getLength();
rtl::OUString sData(chars, len / 2);
//the runtime lib is on the first line
sal_Int32 index = 0;
rtl::OUString aToken = sData.getToken( 1, '\n', index);
rtl::OString paths =
rtl::OUStringToOString(aToken, osl_getThreadTextEncoding());
return paths;
}
static sal_Bool hasOption(char* szOption, int argc, char** argv)
{
sal_Bool retVal= sal_False;
for(sal_Int16 i= 1; i < argc; i++)
{
if( ! strcmp(argv[i], szOption))
{
retVal= sal_True;
break;
}
}
return retVal;
}
<commit_msg>INTEGRATION: CWS valgrind02 (1.5.14); FILE MERGED 2004/10/11 17:26:26 mhu 1.5.14.1: #i35209# Adapted to use SAL_IMPLEMENT_MAIN_WITH_ARGS() macro instead of plain main() function.<commit_after>/*************************************************************************
*
* $RCSfile: javaldx.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2004-10-28 16:24:18 $
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sal/main.h"
#include "sal/types.h"
#include "osl/thread.h"
#include "rtl/ustring.hxx"
#include "rtl/byteseq.hxx"
#include "jvmfwk/framework.h"
using namespace rtl;
#define OUSTR(x) OUString(RTL_CONSTASCII_USTRINGPARAM( x ))
static sal_Bool hasOption(char* szOption, int argc, char** argv);
static rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData);
//static sal_Bool printPaths(const OUString& sPathFile);
#define HELP_TEXT \
"\njavaldx is necessary to make Java work on some UNIX platforms." \
"It prints a string to std out that consists of directories which " \
"have to be included into the LD_LIBRARY_PATH variable.The setting of " \
"the variable usually occurs in a shell script that runs javaldx.\n" \
"The directories are from the chosen java installation. \n" \
"Options are: \n"\
"--help or -h\n"
SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{
if( hasOption("--help",argc, argv) || hasOption("-h", argc, argv))
{
fprintf(stdout, HELP_TEXT);// default
return 0;
}
sal_Bool bEnabled = sal_False;
if (jfw_getEnabled( & bEnabled) != JFW_E_NONE)
{
fprintf(stderr,"javaldx failed! \n");
return -1;
}
if (bEnabled == sal_False)
{
//Do not do any preparation because that may only slow startup time.
return 0;
}
JavaInfo * pInfo = NULL;
javaFrameworkError errcode = JFW_E_NONE;
errcode = jfw_getSelectedJRE( & pInfo);
if (errcode == JFW_E_INVALID_SETTINGS)
{
fprintf(stderr,"javaldx failed. User must select a JRE from options dialog!");
return -1;
}
else if (errcode != JFW_E_NONE)
{
fprintf(stderr,"javaldx failed! \n");
return -1;
}
if (pInfo == NULL)
{
errcode = jfw_findAndSelectJRE( & pInfo);
if (errcode == JFW_E_NO_JAVA_FOUND)
{
fprintf(stderr,"javaldx: Could not find a Java Runtime Environment! \n");
return 0;
}
else if (errcode != JFW_E_NONE)
{
fprintf(stderr,"javaldx failed!\n");
return -1;
}
}
//Only do something if the sunjavaplugin created this JavaInfo
rtl::OUString sVendor1(RTL_CONSTASCII_USTRINGPARAM("Sun Microsystems Inc."));
rtl::OUString sVendor2(RTL_CONSTASCII_USTRINGPARAM("IBM Corporation"));
rtl::OUString sVendor3(RTL_CONSTASCII_USTRINGPARAM("Blackdown Java-Linux Team"));
rtl::OUString sVendor4(RTL_CONSTASCII_USTRINGPARAM("Apple Computer, Inc."));
if ( ! (sVendor1.equals(pInfo->sVendor) == sal_True
|| sVendor2.equals(pInfo->sVendor) == sal_True
|| sVendor3.equals(pInfo->sVendor) == sal_True
|| sVendor4.equals(pInfo->sVendor) == sal_True))
return 0;
rtl::OString sPaths = getLD_LIBRARY_PATH(pInfo->arVendorData);
fprintf(stdout, "%s\n", sPaths.getStr());
jfw_freeJavaInfo(pInfo);
return 0;
}
rtl::OString getLD_LIBRARY_PATH(const rtl::ByteSequence & vendorData)
{
const sal_Unicode* chars = (sal_Unicode*) vendorData.getConstArray();
sal_Int32 len = vendorData.getLength();
rtl::OUString sData(chars, len / 2);
//the runtime lib is on the first line
sal_Int32 index = 0;
rtl::OUString aToken = sData.getToken( 1, '\n', index);
rtl::OString paths =
rtl::OUStringToOString(aToken, osl_getThreadTextEncoding());
return paths;
}
static sal_Bool hasOption(char* szOption, int argc, char** argv)
{
sal_Bool retVal= sal_False;
for(sal_Int16 i= 1; i < argc; i++)
{
if( ! strcmp(argv[i], szOption))
{
retVal= sal_True;
break;
}
}
return retVal;
}
<|endoftext|> |
<commit_before>#include "Iop_SubSystem.h"
#include "../MemoryStateFile.h"
#include "../MA_MIPSIV.h"
#include "../Ps2Const.h"
#include "../Log.h"
#include "placeholder_def.h"
using namespace Iop;
using namespace std::tr1;
using namespace PS2;
#define LOG_NAME ("iop_subsystem")
#define STATE_CPU ("iop_cpu")
#define STATE_RAM ("iop_ram")
#define STATE_SCRATCH ("iop_scratch")
CSubSystem::CSubSystem() :
m_cpu(MEMORYMAP_ENDIAN_LSBF, 0, 0x1FFFFFFF),
m_executor(m_cpu),
m_bios(NULL),
m_ram(new uint8[IOP_RAM_SIZE]),
m_scratchPad(new uint8[IOP_SCRATCH_SIZE]),
m_spuRam(new uint8[SPU_RAM_SIZE]),
m_dmac(m_ram, m_intc),
m_counters(IOP_CLOCK_FREQ, m_intc),
m_spuCore0(m_spuRam, SPU_RAM_SIZE),
m_spuCore1(m_spuRam, SPU_RAM_SIZE),
m_spu(m_spuCore0),
m_spu2(m_spuCore0, m_spuCore1)
{
//Read memory map
m_cpu.m_pMemoryMap->InsertReadMap((0 * IOP_RAM_SIZE), (0 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x01);
m_cpu.m_pMemoryMap->InsertReadMap((1 * IOP_RAM_SIZE), (1 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x02);
m_cpu.m_pMemoryMap->InsertReadMap((2 * IOP_RAM_SIZE), (2 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x03);
m_cpu.m_pMemoryMap->InsertReadMap((3 * IOP_RAM_SIZE), (3 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x04);
m_cpu.m_pMemoryMap->InsertReadMap(0x1F800000, 0x1F8003FF, m_scratchPad, 0x05);
m_cpu.m_pMemoryMap->InsertReadMap(HW_REG_BEGIN, HW_REG_END, bind(&CSubSystem::ReadIoRegister, this, PLACEHOLDER_1), 0x06);
//Write memory map
m_cpu.m_pMemoryMap->InsertWriteMap((0 * IOP_RAM_SIZE), (0 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x01);
m_cpu.m_pMemoryMap->InsertWriteMap((1 * IOP_RAM_SIZE), (1 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x02);
m_cpu.m_pMemoryMap->InsertWriteMap((2 * IOP_RAM_SIZE), (2 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x03);
m_cpu.m_pMemoryMap->InsertWriteMap((3 * IOP_RAM_SIZE), (3 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x04);
m_cpu.m_pMemoryMap->InsertWriteMap(0x1F800000, 0x1F8003FF, m_scratchPad, 0x05);
m_cpu.m_pMemoryMap->InsertWriteMap(HW_REG_BEGIN, HW_REG_END, bind(&CSubSystem::WriteIoRegister, this, PLACEHOLDER_1, PLACEHOLDER_2), 0x06);
//Instruction memory map
m_cpu.m_pMemoryMap->InsertInstructionMap((0 * IOP_RAM_SIZE), (0 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x01);
m_cpu.m_pMemoryMap->InsertInstructionMap((1 * IOP_RAM_SIZE), (1 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x02);
m_cpu.m_pMemoryMap->InsertInstructionMap((2 * IOP_RAM_SIZE), (2 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x03);
m_cpu.m_pMemoryMap->InsertInstructionMap((3 * IOP_RAM_SIZE), (3 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x04);
m_cpu.m_pArch = &g_MAMIPSIV;
m_cpu.m_pAddrTranslator = &CMIPS::TranslateAddress64;
m_dmac.SetReceiveFunction(4, bind(&CSpuBase::ReceiveDma, &m_spuCore0, PLACEHOLDER_1, PLACEHOLDER_2, PLACEHOLDER_3));
m_dmac.SetReceiveFunction(8, bind(&CSpuBase::ReceiveDma, &m_spuCore1, PLACEHOLDER_1, PLACEHOLDER_2, PLACEHOLDER_3));
}
CSubSystem::~CSubSystem()
{
}
void CSubSystem::SetBios(CBiosBase* bios)
{
m_bios = bios;
}
void CSubSystem::SaveState(CZipArchiveWriter& archive)
{
archive.InsertFile(new CMemoryStateFile(STATE_CPU, &m_cpu.m_State, sizeof(MIPSSTATE)));
archive.InsertFile(new CMemoryStateFile(STATE_RAM, m_ram, IOP_RAM_SIZE));
archive.InsertFile(new CMemoryStateFile(STATE_SCRATCH, m_scratchPad, IOP_SCRATCH_SIZE));
m_bios->SaveState(archive);
}
void CSubSystem::LoadState(CZipArchiveReader& archive)
{
archive.BeginReadFile(STATE_CPU )->Read(&m_cpu.m_State, sizeof(MIPSSTATE));
archive.BeginReadFile(STATE_RAM )->Read(m_ram, IOP_RAM_SIZE);
archive.BeginReadFile(STATE_SCRATCH )->Read(m_scratchPad, IOP_SCRATCH_SIZE);
m_bios->LoadState(archive);
}
void CSubSystem::Reset()
{
memset(m_ram, 0, IOP_RAM_SIZE);
memset(m_scratchPad, 0, IOP_SCRATCH_SIZE);
memset(m_spuRam, 0, SPU_RAM_SIZE);
m_executor.Clear();
m_cpu.Reset();
m_spuCore0.Reset();
m_spuCore1.Reset();
m_spu.Reset();
m_spu2.Reset();
m_counters.Reset();
m_dmac.Reset();
m_intc.Reset();
m_bios = NULL;
m_cpu.m_Comments.RemoveTags();
m_cpu.m_Functions.RemoveTags();
}
uint32 CSubSystem::ReadIoRegister(uint32 address)
{
if(address == 0x1F801814)
{
return 0x14802000;
}
else if(address >= CSpu::SPU_BEGIN && address <= CSpu::SPU_END)
{
return m_spu.ReadRegister(address);
}
else if(address >= CDmac::DMAC_ZONE1_START && address <= CDmac::DMAC_ZONE1_END)
{
return m_dmac.ReadRegister(address);
}
else if(address >= CDmac::DMAC_ZONE2_START && address <= CDmac::DMAC_ZONE2_END)
{
return m_dmac.ReadRegister(address);
}
else if(address >= CIntc::ADDR_BEGIN && address <= CIntc::ADDR_END)
{
return m_intc.ReadRegister(address);
}
else if(address >= CRootCounters::ADDR_BEGIN && address <= CRootCounters::ADDR_END)
{
return m_counters.ReadRegister(address);
}
else if(address >= CSpu2::REGS_BEGIN && address <= CSpu2::REGS_END)
{
return m_spu2.ReadRegister(address);
}
else
{
CLog::GetInstance().Print(LOG_NAME, "Reading an unknown hardware register (0x%0.8X).\r\n", address);
}
return 0;
}
uint32 CSubSystem::WriteIoRegister(uint32 address, uint32 value)
{
if(address >= CDmac::DMAC_ZONE1_START && address <= CDmac::DMAC_ZONE1_END)
{
m_dmac.WriteRegister(address, value);
}
else if(address >= CSpu::SPU_BEGIN && address <= CSpu::SPU_END)
{
m_spu.WriteRegister(address, static_cast<uint16>(value));
}
else if(address >= CDmac::DMAC_ZONE2_START && address <= CDmac::DMAC_ZONE2_END)
{
m_dmac.WriteRegister(address, value);
}
else if(address >= CIntc::ADDR_BEGIN && address <= CIntc::ADDR_END)
{
m_intc.WriteRegister(address, value);
}
else if(address >= CRootCounters::ADDR_BEGIN && address <= CRootCounters::ADDR_END)
{
m_counters.WriteRegister(address, value);
}
else if(address >= CSpu2::REGS_BEGIN && address <= CSpu2::REGS_END)
{
return m_spu2.WriteRegister(address, value);
}
else
{
CLog::GetInstance().Print(LOG_NAME, "Writing to an unknown hardware register (0x%0.8X, 0x%0.8X).\r\n", address, value);
}
return 0;
}
unsigned int CSubSystem::ExecuteCpu(bool singleStep)
{
int ticks = 0;
if(!m_cpu.m_State.nHasException)
{
if(m_intc.HasPendingInterrupt())
{
m_bios->HandleInterrupt();
}
}
if(!m_cpu.m_State.nHasException)
{
int quota = singleStep ? 1 : 500;
ticks = quota - m_executor.Execute(quota);
assert(ticks >= 0);
{
if(m_bios->IsIdle())
{
ticks += (quota * 2);
}
else
{
CBasicBlock* nextBlock = m_executor.FindBlockAt(m_cpu.m_State.nPC);
if(nextBlock != NULL && nextBlock->GetSelfLoopCount() > 5000)
{
//Go a little bit faster if we're "stuck"
ticks += (quota * 2);
}
}
}
if(ticks > 0)
{
m_counters.Update(ticks);
m_bios->CountTicks(ticks);
}
}
if(m_cpu.m_State.nHasException)
{
m_bios->HandleException();
}
return ticks;
}
<commit_msg>Fixed memory leak in Iop_SubSystem<commit_after>#include "Iop_SubSystem.h"
#include "../MemoryStateFile.h"
#include "../MA_MIPSIV.h"
#include "../Ps2Const.h"
#include "../Log.h"
#include "placeholder_def.h"
using namespace Iop;
using namespace std::tr1;
using namespace PS2;
#define LOG_NAME ("iop_subsystem")
#define STATE_CPU ("iop_cpu")
#define STATE_RAM ("iop_ram")
#define STATE_SCRATCH ("iop_scratch")
CSubSystem::CSubSystem() :
m_cpu(MEMORYMAP_ENDIAN_LSBF, 0, 0x1FFFFFFF),
m_executor(m_cpu),
m_bios(NULL),
m_ram(new uint8[IOP_RAM_SIZE]),
m_scratchPad(new uint8[IOP_SCRATCH_SIZE]),
m_spuRam(new uint8[SPU_RAM_SIZE]),
m_dmac(m_ram, m_intc),
m_counters(IOP_CLOCK_FREQ, m_intc),
m_spuCore0(m_spuRam, SPU_RAM_SIZE),
m_spuCore1(m_spuRam, SPU_RAM_SIZE),
m_spu(m_spuCore0),
m_spu2(m_spuCore0, m_spuCore1)
{
//Read memory map
m_cpu.m_pMemoryMap->InsertReadMap((0 * IOP_RAM_SIZE), (0 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x01);
m_cpu.m_pMemoryMap->InsertReadMap((1 * IOP_RAM_SIZE), (1 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x02);
m_cpu.m_pMemoryMap->InsertReadMap((2 * IOP_RAM_SIZE), (2 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x03);
m_cpu.m_pMemoryMap->InsertReadMap((3 * IOP_RAM_SIZE), (3 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x04);
m_cpu.m_pMemoryMap->InsertReadMap(0x1F800000, 0x1F8003FF, m_scratchPad, 0x05);
m_cpu.m_pMemoryMap->InsertReadMap(HW_REG_BEGIN, HW_REG_END, bind(&CSubSystem::ReadIoRegister, this, PLACEHOLDER_1), 0x06);
//Write memory map
m_cpu.m_pMemoryMap->InsertWriteMap((0 * IOP_RAM_SIZE), (0 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x01);
m_cpu.m_pMemoryMap->InsertWriteMap((1 * IOP_RAM_SIZE), (1 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x02);
m_cpu.m_pMemoryMap->InsertWriteMap((2 * IOP_RAM_SIZE), (2 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x03);
m_cpu.m_pMemoryMap->InsertWriteMap((3 * IOP_RAM_SIZE), (3 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x04);
m_cpu.m_pMemoryMap->InsertWriteMap(0x1F800000, 0x1F8003FF, m_scratchPad, 0x05);
m_cpu.m_pMemoryMap->InsertWriteMap(HW_REG_BEGIN, HW_REG_END, bind(&CSubSystem::WriteIoRegister, this, PLACEHOLDER_1, PLACEHOLDER_2), 0x06);
//Instruction memory map
m_cpu.m_pMemoryMap->InsertInstructionMap((0 * IOP_RAM_SIZE), (0 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x01);
m_cpu.m_pMemoryMap->InsertInstructionMap((1 * IOP_RAM_SIZE), (1 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x02);
m_cpu.m_pMemoryMap->InsertInstructionMap((2 * IOP_RAM_SIZE), (2 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x03);
m_cpu.m_pMemoryMap->InsertInstructionMap((3 * IOP_RAM_SIZE), (3 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x04);
m_cpu.m_pArch = &g_MAMIPSIV;
m_cpu.m_pAddrTranslator = &CMIPS::TranslateAddress64;
m_dmac.SetReceiveFunction(4, bind(&CSpuBase::ReceiveDma, &m_spuCore0, PLACEHOLDER_1, PLACEHOLDER_2, PLACEHOLDER_3));
m_dmac.SetReceiveFunction(8, bind(&CSpuBase::ReceiveDma, &m_spuCore1, PLACEHOLDER_1, PLACEHOLDER_2, PLACEHOLDER_3));
}
CSubSystem::~CSubSystem()
{
}
void CSubSystem::SetBios(CBiosBase* bios)
{
if(m_bios != NULL)
{
delete m_bios;
m_bios = NULL;
}
m_bios = bios;
}
void CSubSystem::SaveState(CZipArchiveWriter& archive)
{
archive.InsertFile(new CMemoryStateFile(STATE_CPU, &m_cpu.m_State, sizeof(MIPSSTATE)));
archive.InsertFile(new CMemoryStateFile(STATE_RAM, m_ram, IOP_RAM_SIZE));
archive.InsertFile(new CMemoryStateFile(STATE_SCRATCH, m_scratchPad, IOP_SCRATCH_SIZE));
m_bios->SaveState(archive);
}
void CSubSystem::LoadState(CZipArchiveReader& archive)
{
archive.BeginReadFile(STATE_CPU )->Read(&m_cpu.m_State, sizeof(MIPSSTATE));
archive.BeginReadFile(STATE_RAM )->Read(m_ram, IOP_RAM_SIZE);
archive.BeginReadFile(STATE_SCRATCH )->Read(m_scratchPad, IOP_SCRATCH_SIZE);
m_bios->LoadState(archive);
}
void CSubSystem::Reset()
{
memset(m_ram, 0, IOP_RAM_SIZE);
memset(m_scratchPad, 0, IOP_SCRATCH_SIZE);
memset(m_spuRam, 0, SPU_RAM_SIZE);
m_executor.Clear();
m_cpu.Reset();
m_spuCore0.Reset();
m_spuCore1.Reset();
m_spu.Reset();
m_spu2.Reset();
m_counters.Reset();
m_dmac.Reset();
m_intc.Reset();
SetBios(NULL);
m_cpu.m_Comments.RemoveTags();
m_cpu.m_Functions.RemoveTags();
}
uint32 CSubSystem::ReadIoRegister(uint32 address)
{
if(address == 0x1F801814)
{
return 0x14802000;
}
else if(address >= CSpu::SPU_BEGIN && address <= CSpu::SPU_END)
{
return m_spu.ReadRegister(address);
}
else if(address >= CDmac::DMAC_ZONE1_START && address <= CDmac::DMAC_ZONE1_END)
{
return m_dmac.ReadRegister(address);
}
else if(address >= CDmac::DMAC_ZONE2_START && address <= CDmac::DMAC_ZONE2_END)
{
return m_dmac.ReadRegister(address);
}
else if(address >= CIntc::ADDR_BEGIN && address <= CIntc::ADDR_END)
{
return m_intc.ReadRegister(address);
}
else if(address >= CRootCounters::ADDR_BEGIN && address <= CRootCounters::ADDR_END)
{
return m_counters.ReadRegister(address);
}
else if(address >= CSpu2::REGS_BEGIN && address <= CSpu2::REGS_END)
{
return m_spu2.ReadRegister(address);
}
else
{
CLog::GetInstance().Print(LOG_NAME, "Reading an unknown hardware register (0x%0.8X).\r\n", address);
}
return 0;
}
uint32 CSubSystem::WriteIoRegister(uint32 address, uint32 value)
{
if(address >= CDmac::DMAC_ZONE1_START && address <= CDmac::DMAC_ZONE1_END)
{
m_dmac.WriteRegister(address, value);
}
else if(address >= CSpu::SPU_BEGIN && address <= CSpu::SPU_END)
{
m_spu.WriteRegister(address, static_cast<uint16>(value));
}
else if(address >= CDmac::DMAC_ZONE2_START && address <= CDmac::DMAC_ZONE2_END)
{
m_dmac.WriteRegister(address, value);
}
else if(address >= CIntc::ADDR_BEGIN && address <= CIntc::ADDR_END)
{
m_intc.WriteRegister(address, value);
}
else if(address >= CRootCounters::ADDR_BEGIN && address <= CRootCounters::ADDR_END)
{
m_counters.WriteRegister(address, value);
}
else if(address >= CSpu2::REGS_BEGIN && address <= CSpu2::REGS_END)
{
return m_spu2.WriteRegister(address, value);
}
else
{
CLog::GetInstance().Print(LOG_NAME, "Writing to an unknown hardware register (0x%0.8X, 0x%0.8X).\r\n", address, value);
}
return 0;
}
unsigned int CSubSystem::ExecuteCpu(bool singleStep)
{
int ticks = 0;
if(!m_cpu.m_State.nHasException)
{
if(m_intc.HasPendingInterrupt())
{
m_bios->HandleInterrupt();
}
}
if(!m_cpu.m_State.nHasException)
{
int quota = singleStep ? 1 : 500;
ticks = quota - m_executor.Execute(quota);
assert(ticks >= 0);
{
if(m_bios->IsIdle())
{
ticks += (quota * 2);
}
else
{
CBasicBlock* nextBlock = m_executor.FindBlockAt(m_cpu.m_State.nPC);
if(nextBlock != NULL && nextBlock->GetSelfLoopCount() > 5000)
{
//Go a little bit faster if we're "stuck"
ticks += (quota * 2);
}
}
}
if(ticks > 0)
{
m_counters.Update(ticks);
m_bios->CountTicks(ticks);
}
}
if(m_cpu.m_State.nHasException)
{
m_bios->HandleException();
}
return ticks;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007-2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/assert.hpp"
#include "libtorrent/puff.hpp"
#include <vector>
#include <string>
namespace
{
enum
{
FTEXT = 0x01,
FHCRC = 0x02,
FEXTRA = 0x04,
FNAME = 0x08,
FCOMMENT = 0x10,
FRESERVED = 0xe0,
GZIP_MAGIC0 = 0x1f,
GZIP_MAGIC1 = 0x8b
};
}
namespace libtorrent
{
// returns -1 if gzip header is invalid or the header size in bytes
int gzip_header(const char* buf, int size)
{
TORRENT_ASSERT(buf != 0);
const unsigned char* buffer = reinterpret_cast<const unsigned char*>(buf);
const int total_size = size;
// The zip header cannot be shorter than 10 bytes
if (size < 10 || buf == 0) return -1;
// check the magic header of gzip
if ((buffer[0] != GZIP_MAGIC0) || (buffer[1] != GZIP_MAGIC1)) return -1;
int method = buffer[2];
int flags = buffer[3];
// check for reserved flag and make sure it's compressed with the correct metod
if (method != 8 || (flags & FRESERVED) != 0) return -1;
// skip time, xflags, OS code
size -= 10;
buffer += 10;
if (flags & FEXTRA)
{
int extra_len;
if (size < 2) return -1;
extra_len = (buffer[1] << 8) | buffer[0];
if (size < (extra_len+2)) return -1;
size -= (extra_len + 2);
buffer += (extra_len + 2);
}
if (flags & FNAME)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FCOMMENT)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FHCRC)
{
if (size < 2) return -1;
size -= 2;
// buffer += 2;
}
return total_size - size;
}
// TODO: 2 it would be nice to use proper error handling here
bool inflate_gzip(
char const* in
, int size
, std::vector<char>& buffer
, int maximum_size
, std::string& error)
{
TORRENT_ASSERT(maximum_size > 0);
int header_len = gzip_header(in, size);
if (header_len < 0)
{
error = "invalid gzip header";
return true;
}
// start off with 4 kilobytes and grow
// if needed
boost::uint32_t destlen = 4096;
int ret = 0;
boost::uint32_t srclen = size - header_len;
in += header_len;
do
{
TORRENT_TRY {
buffer.resize(destlen);
} TORRENT_CATCH(std::exception& e) {
error = "out of memory";
return true;
}
ret = puff((unsigned char*)&buffer[0], &destlen, (unsigned char*)in, &srclen);
// if the destination buffer wasn't large enough, double its
// size and try again. Unless it's already at its max, in which
// case we fail
if (ret == 1) // 1: output space exhausted before completing inflate
{
if (destlen == maximum_size)
{
error = "inflated data too big";
return true;
}
destlen *= 2;
if (destlen > maximum_size)
destlen = maximum_size;
}
} while (ret == 1);
if (ret != 0)
{
error = "error while inflating data";
return true;
}
if (destlen > buffer.size())
{
error = "internal gzip error";
return true;
}
buffer.resize(destlen);
return false;
}
}
<commit_msg>fix inflate_gzip export for unit test<commit_after>/*
Copyright (c) 2007-2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/assert.hpp"
#include "libtorrent/puff.hpp"
#include <vector>
#include <string>
namespace
{
enum
{
FTEXT = 0x01,
FHCRC = 0x02,
FEXTRA = 0x04,
FNAME = 0x08,
FCOMMENT = 0x10,
FRESERVED = 0xe0,
GZIP_MAGIC0 = 0x1f,
GZIP_MAGIC1 = 0x8b
};
}
namespace libtorrent
{
// returns -1 if gzip header is invalid or the header size in bytes
int gzip_header(const char* buf, int size)
{
TORRENT_ASSERT(buf != 0);
const unsigned char* buffer = reinterpret_cast<const unsigned char*>(buf);
const int total_size = size;
// The zip header cannot be shorter than 10 bytes
if (size < 10 || buf == 0) return -1;
// check the magic header of gzip
if ((buffer[0] != GZIP_MAGIC0) || (buffer[1] != GZIP_MAGIC1)) return -1;
int method = buffer[2];
int flags = buffer[3];
// check for reserved flag and make sure it's compressed with the correct metod
if (method != 8 || (flags & FRESERVED) != 0) return -1;
// skip time, xflags, OS code
size -= 10;
buffer += 10;
if (flags & FEXTRA)
{
int extra_len;
if (size < 2) return -1;
extra_len = (buffer[1] << 8) | buffer[0];
if (size < (extra_len+2)) return -1;
size -= (extra_len + 2);
buffer += (extra_len + 2);
}
if (flags & FNAME)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FCOMMENT)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FHCRC)
{
if (size < 2) return -1;
size -= 2;
// buffer += 2;
}
return total_size - size;
}
// TODO: 2 it would be nice to use proper error handling here
TORRENT_EXTRA_EXPORT bool inflate_gzip(
char const* in
, int size
, std::vector<char>& buffer
, int maximum_size
, std::string& error)
{
TORRENT_ASSERT(maximum_size > 0);
int header_len = gzip_header(in, size);
if (header_len < 0)
{
error = "invalid gzip header";
return true;
}
// start off with 4 kilobytes and grow
// if needed
boost::uint32_t destlen = 4096;
int ret = 0;
boost::uint32_t srclen = size - header_len;
in += header_len;
do
{
TORRENT_TRY {
buffer.resize(destlen);
} TORRENT_CATCH(std::exception& e) {
error = "out of memory";
return true;
}
ret = puff((unsigned char*)&buffer[0], &destlen, (unsigned char*)in, &srclen);
// if the destination buffer wasn't large enough, double its
// size and try again. Unless it's already at its max, in which
// case we fail
if (ret == 1) // 1: output space exhausted before completing inflate
{
if (destlen == maximum_size)
{
error = "inflated data too big";
return true;
}
destlen *= 2;
if (destlen > maximum_size)
destlen = maximum_size;
}
} while (ret == 1);
if (ret != 0)
{
error = "error while inflating data";
return true;
}
if (destlen > buffer.size())
{
error = "internal gzip error";
return true;
}
buffer.resize(destlen);
return false;
}
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/pda.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,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 */
<commit_msg>Adds PDA support<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/pda.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,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 pda.C
/// @brief Code to support per-DRAM addressability (PDA)
///
// *HWP HWP Owner: Stephen Glancy <[email protected]>
// *HWP HWP Backup: Louis Stermole <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB Memory Lab
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <generic/memory/lib/utils/c_str.H>
#include <generic/memory/lib/utils/find.H>
#include <lib/ccs/ccs.H>
#include <lib/dimm/mrs_load.H>
#include <lib/dimm/ddr4/mrs_load_ddr4.H>
#include <lib/dimm/ddr4/latch_wr_vref.H>
#include <lib/phy/write_cntrl.H>
#include <lib/phy/dp16.H>
#include <lib/dimm/ddr4/pda.H>
#include <lib/workarounds/ccs_workarounds.H>
namespace mss
{
namespace ddr4
{
namespace pda
{
const std::vector<std::pair<uint64_t, uint64_t>> pdaBitTraits<fapi2::ENUM_ATTR_EFF_DRAM_WIDTH_X4>::BIT_MAP =
{
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N0},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N1},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N2},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N3},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_1, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N0},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_1, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N1},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_1, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N2},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_1, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N3},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_2, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N0},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_2, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N1},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_2, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N2},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_2, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N3},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_3, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N0},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_3, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N1},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_3, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N2},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_3, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N3},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_4, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N0},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_4, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N1},
};
const std::vector<std::pair<uint64_t, uint64_t>> pdaBitTraits<fapi2::ENUM_ATTR_EFF_DRAM_WIDTH_X8>::BIT_MAP =
{
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N0},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N2},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_1, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N0},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_1, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N2},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_2, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N0},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_2, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N2},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_3, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N0},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_3, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N2},
{MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_4, MCA_DDRPHY_DP16_DATA_BIT_ENABLE1_P0_0_01_MRS_CMD_N0},
};
///
/// @brief Helper function for changing the DRAM bit
/// @tparam W the DRAM width
/// @tparam TT the DRAM width traits class
/// @param[in] i_target - the MCA target
/// @param[in] i_dram - the DRAM on which to operate
/// @param[in] i_state - the state to write the bit(s) to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template< uint8_t W, typename TT = pdaBitTraits<W> >
fapi2::ReturnCode change_dram_bit_helper( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const uint64_t i_dram,
const mss::states& i_state)
{
fapi2::buffer<uint64_t> l_data;
// Note: the following avoids "undefined reference to" errors due to the set max dram below
// The use of traits and a const reference messes with it
constexpr auto NUM_DRAM = TT::NUM_DRAMS;
// Check bounds
FAPI_ASSERT(i_dram < NUM_DRAM,
fapi2::MSS_PDA_DRAM_OUT_OF_RANGE().
set_MCA_TARGET(i_target).
set_DRAM(i_dram).
set_MAX_DRAM(NUM_DRAM),
"%s was passed DRAM value of %lu which is not below the max value of %lu",
mss::c_str(i_target), i_dram, NUM_DRAM);
FAPI_TRY(mss::getScom(i_target, TT::BIT_MAP[i_dram].first, l_data));
FAPI_TRY(l_data.writeBit(i_state, TT::BIT_MAP[i_dram].second, TT::NUM_BITS));
FAPI_TRY(mss::putScom(i_target, TT::BIT_MAP[i_dram].first, l_data));
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Writes the data bit enable for the properly inputted DRAM
/// @param[in] i_target - the MCA target
/// @param[in] i_dram - the DRAM on which to operate
/// @param[in] i_state - the state to write the bit(s) to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
fapi2::ReturnCode change_dram_bit( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const uint64_t i_dram,
const mss::states& i_state)
{
uint8_t l_dram_width[MAX_DIMM_PER_PORT] = {0};
FAPI_TRY(mss::eff_dram_width(i_target, &(l_dram_width[0])), "Failed to get the DRAM's width for %s",
mss::c_str(i_target));
{
const auto& l_dimms = mss::find_targets<fapi2::TARGET_TYPE_DIMM>(i_target);
FAPI_ASSERT((l_dram_width[0] == fapi2::ENUM_ATTR_EFF_DRAM_WIDTH_X4) ||
(l_dram_width[0] == fapi2::ENUM_ATTR_EFF_DRAM_WIDTH_X8),
fapi2::MSS_INVALID_DRAM_WIDTH().
set_DIMM_TARGET(l_dimms[0]).
set_DRAM_WIDTH(l_dram_width[0]),
"%s DRAM width was not x4 or x8 - %lu", mss::c_str(i_target), l_dram_width[0]);
}
// We only need to check DIMM 0 due to the plug rules
// x4 DIMM
if(l_dram_width[0] == fapi2::ENUM_ATTR_EFF_DRAM_WIDTH_X4)
{
FAPI_TRY(change_dram_bit_helper<fapi2::ENUM_ATTR_EFF_DRAM_WIDTH_X4>(i_target, i_dram, i_state));
}
// x8 DIMM. The else is ok here as we checked the widths above
else
{
FAPI_TRY(change_dram_bit_helper<fapi2::ENUM_ATTR_EFF_DRAM_WIDTH_X8>(i_target, i_dram, i_state));
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Configures all DRAM level configuration bits to the inputted settings
/// @param[in] i_target a fapi2::Target MCA
/// @param[in] i_state - OFF_N - 1's, ON_N - 0's
/// @return FAPI2_RC_SUCCESS if and only if ok
/// @note PDA is LOW enable, so 0's means ON. ON will configure the register to 0's - using OFF/ON_N
///
fapi2::ReturnCode blast_dram_config( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, const mss::states& i_state )
{
typedef mss::dp16Traits<fapi2::TARGET_TYPE_MCA> TT;
std::vector<fapi2::buffer<uint64_t>> l_reg_data;
// Gets the register data
FAPI_TRY(mss::scom_suckah(i_target, TT::DATA_BIT_ENABLE1, l_reg_data));
// Loops and modifies the data
for(auto& l_data : l_reg_data)
{
// Remember 1 = OFF
set_dram_enable<DRAM0>(l_data, i_state);
set_dram_enable<DRAM1>(l_data, i_state);
set_dram_enable<DRAM2>(l_data, i_state);
set_dram_enable<DRAM3>(l_data, i_state);
}
// Blasts the data back out
FAPI_TRY(mss::scom_blastah(i_target, TT::DATA_BIT_ENABLE1, l_reg_data));
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Configures PDA timings
/// @param[in] i_target a fapi2::Target MCA
/// @return FAPI2_RC_SUCCESS if and only if ok
///
fapi2::ReturnCode configure_timings( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target )
{
// Fun fact, we're hitting all of the bits in this reg, no need for RMW
fapi2::buffer<uint64_t> l_data;
// So we want to:
// 1) Turn on the PDA on MRS bit
// 2) Have a 0 delay between the MRS being sent and starting the 0/1 latching
// 3) Hold the delay for as long as possible (safer and easier than figuring out how long to hold the values)
mss::wc::set_pda_mode(l_data, mss::states::ON);
mss::wc::set_pda_dq_on_delay(l_data, START_DELAY_VALUE);
mss::wc::set_pda_dq_off_delay(l_data, HOLD_DELAY_VALUE);
// Set that reg
FAPI_TRY(mss::wc::write_config3(i_target, l_data));
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Adds a PDA enable command
/// @param[in] i_target a fapi2::Target DIMM
/// @param[in] i_rank the rank to send to
/// @param[in,out] io_inst the CCS instructions to update
/// @return FAPI2_RC_SUCCESS if and only if ok
///
fapi2::ReturnCode add_enable( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const uint64_t i_rank,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst )
{
mss::ddr4::mrs03_data l_mrs03( i_target, fapi2::current_err );
FAPI_TRY( fapi2::current_err, "%s Unable to construct MRS03 data from attributes", mss::c_str(i_target));
// Overrides the PDA value to be enabled
l_mrs03.iv_pda = fapi2::ENUM_ATTR_EFF_PER_DRAM_ACCESS_ENABLE;
FAPI_TRY( mss::mrs_engine(i_target, l_mrs03, i_rank, DELAY, io_inst) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Enters into and configures PDA mode
/// @param[in] i_target a fapi2::Target DIMM
/// @param[in] i_rank the rank to send to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
fapi2::ReturnCode enter( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const uint64_t i_rank )
{
ccs::program<fapi2::TARGET_TYPE_MCBIST> l_program;
const auto& l_mca = mss::find_target<fapi2::TARGET_TYPE_MCA>(i_target);
FAPI_TRY( add_enable(i_target, i_rank, l_program.iv_instructions) );
FAPI_TRY( ccs::execute(mss::find_target<fapi2::TARGET_TYPE_MCBIST>(i_target),
l_program,
l_mca),
"unable to execute CCS for MR03 rank %d %s",
i_rank, mss::c_str(i_target) );
// Now sets up all of the PDA regs now that we are in PDA mode
FAPI_TRY(configure_timings(l_mca));
FAPI_TRY(blast_dram_config(l_mca, mss::states::OFF_N));
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Adds a PDA disable command
/// @param[in] i_target a fapi2::Target DIMM
/// @param[in] i_rank the rank to send to
/// @param[in,out] io_inst the instructions
/// @return FAPI2_RC_SUCCESS if and only if ok
///
fapi2::ReturnCode add_disable( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const uint64_t i_rank,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst )
{
mss::ddr4::mrs03_data l_mrs03( i_target, fapi2::current_err );
FAPI_TRY( fapi2::current_err, "%s Unable to construct MRS03 data from attributes", mss::c_str(i_target));
// Overrides the PDA value to be disabled
l_mrs03.iv_pda = fapi2::ENUM_ATTR_EFF_PER_DRAM_ACCESS_DISABLE;
FAPI_TRY( mss::mrs_engine(i_target, l_mrs03, i_rank, DELAY, io_inst) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Exits out of and disables PDA mode
/// @param[in] i_target a fapi2::Target DIMM
/// @param[in] i_rank the rank to send to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
fapi2::ReturnCode exit( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const uint64_t i_rank )
{
ccs::program<fapi2::TARGET_TYPE_MCBIST> l_program;
const auto& l_mca = mss::find_target<fapi2::TARGET_TYPE_MCA>(i_target);
// We need everyone to exit PDA mode, so all of them are all ON
FAPI_TRY(blast_dram_config(l_mca, mss::states::ON_N));
FAPI_TRY( add_disable(i_target, i_rank, l_program.iv_instructions) );
FAPI_TRY( mss::ccs::workarounds::exit(i_target, i_rank, l_program) );
FAPI_TRY( ccs::execute(mss::find_target<fapi2::TARGET_TYPE_MCBIST>(i_target),
l_program,
l_mca),
"unable to execute CCS for MR03 PDA exit rank %d %s",
i_rank, mss::c_str(i_target) );
// Disables PDA mode
{
fapi2::buffer<uint64_t> l_data;
FAPI_TRY(mss::wc::read_config3(l_mca, l_data));
mss::wc::set_pda_mode(l_data, mss::states::OFF);
FAPI_TRY(mss::wc::write_config3(l_mca, l_data));
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Performs a PDA WR VREF latch
/// @param[in] i_target a fapi2::Target DIMM
/// @param[in] i_rank the rank to send to
/// @param[in] i_mrs the MRS data to update
/// @param[in] i_drams the DRAM to update
/// @return FAPI2_RC_SUCCESS if and only if ok
/// @note A PDA latch of WR VREF settings is the most common PDA operations
/// This function adds a bit of fanciness (compression) to speed up the overall runtime
///
fapi2::ReturnCode execute_wr_vref_latch( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const uint64_t i_rank,
const mss::ddr4::mrs06_data& i_mrs,
const std::vector<uint64_t>& i_drams )
{
const auto& l_mca = mss::find_target<fapi2::TARGET_TYPE_MCA>(i_target);
// If the commands passed in are empty, simply exit
FAPI_ASSERT((!i_drams.empty()),
fapi2::MSS_EMPTY_PDA_VECTOR().
set_PROCEDURE(mss::ffdc_function_codes::PDA_WR_VREF_LATCH_VECTOR),
"%s PDA commands vector is empty, exiting", mss::c_str(i_target));
// Enable all individual DRAM
for(const auto l_dram : i_drams)
{
FAPI_TRY(change_dram_bit( l_mca, l_dram, mss::states::ON_N));
}
// Issue MRS commands
{
ccs::program<fapi2::TARGET_TYPE_MCBIST> l_program;
FAPI_TRY(mss::ddr4::add_latch_wr_vref_commands( i_target,
i_mrs,
i_rank,
l_program.iv_instructions));
FAPI_TRY( ccs::execute(mss::find_target<fapi2::TARGET_TYPE_MCBIST>(i_target),
l_program,
l_mca),
"unable to execute CCS for MR06 rank %d %s",
i_rank, mss::c_str(i_target) );
}
// Disable all individual DRAM
for(const auto l_dram : i_drams)
{
FAPI_TRY(change_dram_bit( l_mca, l_dram, mss::states::OFF_N));
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Performs a PDA WR VREF latch
/// @param[in] i_commands the PDA commands to issue and DRAM
/// @return FAPI2_RC_SUCCESS if and only if ok
/// @note A PDA latch of WR VREF settings is the most common PDA operations
/// This function adds a bit of fanciness (compression) to speed up the overall runtime
///
fapi2::ReturnCode execute_wr_vref_latch( const commands<mss::ddr4::mrs06_data>& i_commands )
{
// If the commands passed in are empty, simply exit
FAPI_ASSERT((!i_commands.empty()),
fapi2::MSS_EMPTY_PDA_VECTOR().
set_PROCEDURE(mss::ffdc_function_codes::PDA_WR_VREF_LATCH_CONTAINER),
"PDA commands map is empty, exiting");
// Loop until all commands have been issued
for(const auto& l_commands : i_commands.get())
{
// PDA targetting information - stores both the DIMM and rank in a pair
const auto& l_target_info = l_commands.first;
const auto& l_dimm = l_target_info.first;
const auto l_rank = l_target_info.second;
// The PDA commands consist of MRS's and their associated DRAM's
const auto& l_pda_commands = l_commands.second;
// First, enter into PDA mode
FAPI_TRY(enter(l_dimm, l_rank));
// Now loops through all of the MRS and DRAM
for(const auto& l_command : l_pda_commands)
{
const auto& l_mrs = l_command.first;
const auto& l_drams = l_command.second;
FAPI_TRY(execute_wr_vref_latch( l_dimm,
l_rank,
l_mrs,
l_drams ));
}
// Finally, exit out of PDA
FAPI_TRY(exit(l_dimm, l_rank));
}
fapi_try_exit:
return fapi2::current_err;
}
} // ns pda
} // ns ddr4
} // ns mss
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: chips/p9/procedures/hwp/perv/p9_setup_sbe_config.C $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* EKB Project */
/* */
/* COPYRIGHT 2015,2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_setup_sbe_config.C
///
/// @brief proc setup sbe config
//------------------------------------------------------------------------------
// *HWP HW Owner : Anusha Reddy Rangareddygari <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Brian Silver <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : SBE
//------------------------------------------------------------------------------
//## auto_generated
#include "p9_setup_sbe_config.H"
#include <p9_perv_scom_addresses.H>
enum P9_SETUP_SBE_CONFIG_Private_Constants
{
ATTR_EQ_GARD_STARTBIT = 0,
ATTR_EQ_GARD_LENGTH = 6,
ATTR_EC_GARD_STARTBIT = 8,
ATTR_EC_GARD_LENGTH = 24,
ATTR_I2C_BUS_DIV_REF_STARTBIT = 0,
ATTR_I2C_BUS_DIV_REF_LENGTH = 16,
ATTR_BOOT_FLAGS_STARTBIT = 0,
ATTR_BOOT_FLAGS_LENGTH = 32,
ATTR_PROC_FABRIC_GROUP_ID_STARTBIT = 26,
ATTR_PROC_FABRIC_GROUP_ID_LENGTH = 3,
ATTR_PROC_FABRIC_CHIP_ID_STARTBIT = 29,
ATTR_PROC_FABRIC_CHIP_ID_LENGTH = 3,
ATTR_BOOT_FREQ_MULT_STARTBIT = 0,
ATTR_BOOT_FREQ_MULT_LENGTH = 16,
ATTR_NEST_PLL_BUCKET_STARTBIT = 24,
ATTR_NEST_PLL_BUCKET_LENGTH = 8
};
fapi2::ReturnCode p9_setup_sbe_config(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
fapi2::buffer<uint32_t> l_read_scratch_reg = 0;
fapi2::buffer<uint32_t> l_read_scratch8 = 0;
fapi2::buffer<uint8_t> l_read_1 = 0;
fapi2::buffer<uint8_t> l_read_2 = 0;
fapi2::buffer<uint8_t> l_read_3 = 0;
fapi2::buffer<uint16_t> l_read_4 = 0;
fapi2::buffer<uint32_t> l_read_5 = 0;
fapi2::buffer<uint32_t> l_read_6 = 0;
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
FAPI_INF("Entering ...");
FAPI_DBG("Read Scratch8 for validity of Scratch register");
//Getting SCRATCH_REGISTER_8 register value
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_8_FSI,
l_read_scratch8)); //l_read_scratch8 = CFAM.SCRATCH_REGISTER_8
//set_scratch1_reg
{
FAPI_DBG("Read Scratch_reg1");
//Getting SCRATCH_REGISTER_1 register value
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_1_FSI,
l_read_scratch_reg)); //l_read_scratch_reg = CFAM.SCRATCH_REGISTER_1
FAPI_DBG("Reading ATTR_EQ_GARD, ATTR_EC_GARD");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EQ_GARD, i_target_chip, l_read_1));
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EC_GARD, i_target_chip, l_read_5));
l_read_1.extractToRight< 0, ATTR_EQ_GARD_LENGTH >(l_read_2);
l_read_5.extractToRight< 0, ATTR_EC_GARD_LENGTH >(l_read_6);
l_read_scratch_reg.insertFromRight< ATTR_EQ_GARD_STARTBIT, ATTR_EQ_GARD_LENGTH >(l_read_2);
l_read_scratch_reg.insertFromRight< ATTR_EC_GARD_STARTBIT, ATTR_EC_GARD_LENGTH >(l_read_6);
FAPI_DBG("Setting up value of Scratch_reg1");
//Setting SCRATCH_REGISTER_1 register value
//CFAM.SCRATCH_REGISTER_1 = l_read_scratch_reg
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_1_FSI,
l_read_scratch_reg));
l_read_scratch8.setBit<0>();
}
//set_scratch2_reg
{
FAPI_DBG("Reading Scratch_reg2");
//Getting SCRATCH_REGISTER_2 register value
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_2_FSI,
l_read_scratch_reg)); //l_read_scratch_reg = CFAM.SCRATCH_REGISTER_2
FAPI_DBG("Reading ATTR_I2C_BUS_DIV_REF");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_I2C_BUS_DIV_REF, i_target_chip, l_read_4));
l_read_scratch_reg.insertFromRight< ATTR_I2C_BUS_DIV_REF_STARTBIT, ATTR_I2C_BUS_DIV_REF_LENGTH >(l_read_4);
FAPI_DBG("Setting up value of Scratch_reg2");
//Setting SCRATCH_REGISTER_2 register value
//CFAM.SCRATCH_REGISTER_2 = l_read_scratch_reg
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_2_FSI,
l_read_scratch_reg));
l_read_scratch8.setBit<1>();
}
//set_scratch3_reg
{
FAPI_DBG("Reading Scratch_reg3");
//Getting SCRATCH_REGISTER_3 register value
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_3_FSI,
l_read_scratch_reg)); //l_read_scratch_reg = CFAM.SCRATCH_REGISTER_3
FAPI_DBG("Reading the BOOT_FLAGS");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_BOOT_FLAGS, FAPI_SYSTEM, l_read_5));
l_read_scratch_reg.insertFromRight< ATTR_BOOT_FLAGS_STARTBIT, ATTR_BOOT_FLAGS_LENGTH >(l_read_5);
FAPI_DBG("Setting up value of Scratch_reg3");
//Setting SCRATCH_REGISTER_3 register value
//CFAM.SCRATCH_REGISTER_3 = l_read_scratch_reg
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_3_FSI,
l_read_scratch_reg));
l_read_scratch8.setBit<2>();
}
//set_scratch4_reg
{
FAPI_DBG("Reading Scratch_reg4");
//Getting SCRATCH_REGISTER_4 register value
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_4_FSI,
l_read_scratch_reg)); //l_read_scratch_reg = CFAM.SCRATCH_REGISTER_4
FAPI_DBG("Reading ATTR_BOOT_FREQ_MULT, ATTR_NEST_PLL_BUCKET");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_BOOT_FREQ_MULT, i_target_chip, l_read_4));
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_NEST_PLL_BUCKET, FAPI_SYSTEM, l_read_1));
l_read_scratch_reg.insertFromRight< ATTR_BOOT_FREQ_MULT_STARTBIT, ATTR_BOOT_FREQ_MULT_LENGTH >(l_read_4);
l_read_scratch_reg.insertFromRight< ATTR_NEST_PLL_BUCKET_STARTBIT, ATTR_NEST_PLL_BUCKET_LENGTH >(l_read_1);
FAPI_DBG("Setting up value of Scratch_reg4");
//Setting SCRATCH_REGISTER_4 register value
//CFAM.SCRATCH_REGISTER_4 = l_read_scratch_reg
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_4_FSI,
l_read_scratch_reg));
l_read_scratch8.setBit<3>();
}
//set_scratch5_reg
{
FAPI_DBG("Reading Scratch_reg5");
//Getting SCRATCH_REGISTER_5 register value
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_5_FSI,
l_read_scratch_reg)); //l_read_scratch_reg = CFAM.SCRATCH_REGISTER_5
FAPI_DBG("Reading the control flags : SYSTEM_IPL_PHASE, RISK_LEVEL, SYS_FORCE_ALL_CORES");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_IPL_PHASE, FAPI_SYSTEM, l_read_1));
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_RISK_LEVEL, FAPI_SYSTEM, l_read_2));
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYS_FORCE_ALL_CORES, FAPI_SYSTEM,
l_read_3));
l_read_scratch_reg.writeBit<0>(l_read_1.getBit<7>());
l_read_scratch_reg.writeBit<1>(l_read_3.getBit<7>());
l_read_scratch_reg.writeBit<2>(l_read_2.getBit<7>());
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_DISABLE_HBBL_VECTORS, FAPI_SYSTEM,
l_read_1));
l_read_scratch_reg.writeBit<3>(l_read_1.getBit<7>());
FAPI_DBG("Setting up value of Scratch_reg5");
//Setting SCRATCH_REGISTER_5 register value
//CFAM.SCRATCH_REGISTER_5 = l_read_scratch_reg
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_5_FSI,
l_read_scratch_reg));
l_read_scratch8.setBit<4>();
}
//set_scratch6_reg
{
FAPI_DBG("Reading Scratch_reg6");
//Getting SCRATCH_REGISTER_6 register value
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_6_FSI,
l_read_scratch_reg)); //l_read_scratch_reg = CFAM.SCRATCH_REGISTER_6
FAPI_DBG("Reading attribute for Hostboot slave bit");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_SBE_MASTER_CHIP, i_target_chip,
l_read_1));
l_read_scratch_reg.writeBit<24>(l_read_1.getBit<7>());
FAPI_DBG("Reading ATTR_PROC_FABRIC_GROUP and CHIP_ID");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_GROUP_ID, i_target_chip,
l_read_1));
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_CHIP_ID, i_target_chip,
l_read_2));
l_read_scratch_reg.insertFromRight< ATTR_PROC_FABRIC_GROUP_ID_STARTBIT, ATTR_PROC_FABRIC_GROUP_ID_LENGTH >(l_read_1);
l_read_scratch_reg.insertFromRight< ATTR_PROC_FABRIC_CHIP_ID_STARTBIT, ATTR_PROC_FABRIC_CHIP_ID_LENGTH >(l_read_2);
FAPI_DBG("Setting up value of Scratch_reg6");
//Setting SCRATCH_REGISTER_6 register value
//CFAM.SCRATCH_REGISTER_6 = l_read_scratch_reg
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_6_FSI,
l_read_scratch_reg));
l_read_scratch8.setBit<5>();
}
FAPI_DBG("Setting Scratch8 for validity of Scratch register");
//Setting SCRATCH_REGISTER_8 register value
//CFAM.SCRATCH_REGISTER_8 = l_read_scratch8
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_8_FSI,
l_read_scratch8));
FAPI_INF("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>Level 2 HWP for p9_setup_sbe_config<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: chips/p9/procedures/hwp/perv/p9_setup_sbe_config.C $ */
/* */
/* IBM CONFIDENTIAL */
/* */
/* EKB Project */
/* */
/* COPYRIGHT 2015,2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* The source code for this program is not published or otherwise */
/* divested of its trade secrets, irrespective of what has been */
/* deposited with the U.S. Copyright Office. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_setup_sbe_config.C
///
/// @brief proc setup sbe config
//------------------------------------------------------------------------------
// *HWP HW Owner : Anusha Reddy Rangareddygari <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Brian Silver <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : SBE
//------------------------------------------------------------------------------
//## auto_generated
#include "p9_setup_sbe_config.H"
#include <p9_perv_scom_addresses.H>
enum P9_SETUP_SBE_CONFIG_Private_Constants
{
ATTR_EQ_GARD_STARTBIT = 0,
ATTR_EQ_GARD_LENGTH = 6,
ATTR_EC_GARD_STARTBIT = 8,
ATTR_EC_GARD_LENGTH = 24,
ATTR_I2C_BUS_DIV_REF_STARTBIT = 0,
ATTR_I2C_BUS_DIV_REF_LENGTH = 16,
ATTR_BOOT_FLAGS_STARTBIT = 0,
ATTR_BOOT_FLAGS_LENGTH = 32,
ATTR_PROC_FABRIC_GROUP_ID_STARTBIT = 26,
ATTR_PROC_FABRIC_GROUP_ID_LENGTH = 3,
ATTR_PROC_FABRIC_CHIP_ID_STARTBIT = 29,
ATTR_PROC_FABRIC_CHIP_ID_LENGTH = 3,
ATTR_BOOT_FREQ_MULT_STARTBIT = 0,
ATTR_BOOT_FREQ_MULT_LENGTH = 16,
ATTR_NEST_PLL_BUCKET_STARTBIT = 24,
ATTR_NEST_PLL_BUCKET_LENGTH = 8
};
fapi2::ReturnCode p9_setup_sbe_config(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
fapi2::buffer<uint32_t> l_read_scratch_reg = 0;
fapi2::buffer<uint32_t> l_read_scratch8 = 0;
fapi2::buffer<uint8_t> l_read_1 = 0;
fapi2::buffer<uint8_t> l_read_2 = 0;
fapi2::buffer<uint8_t> l_read_3 = 0;
fapi2::buffer<uint16_t> l_read_4 = 0;
fapi2::buffer<uint32_t> l_read_5 = 0;
fapi2::buffer<uint32_t> l_read_6 = 0;
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
FAPI_INF("Entering ...");
FAPI_DBG("Read Scratch8 for validity of Scratch register");
//Getting SCRATCH_REGISTER_8 register value
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_8_FSI,
l_read_scratch8)); //l_read_scratch8 = CFAM.SCRATCH_REGISTER_8
//set_scratch1_reg
{
FAPI_DBG("Read Scratch_reg1");
//Getting SCRATCH_REGISTER_1 register value
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_1_FSI,
l_read_scratch_reg)); //l_read_scratch_reg = CFAM.SCRATCH_REGISTER_1
FAPI_DBG("Reading ATTR_EQ_GARD, ATTR_EC_GARD");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EQ_GARD, i_target_chip, l_read_1));
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EC_GARD, i_target_chip, l_read_5));
l_read_1.extractToRight< 0, ATTR_EQ_GARD_LENGTH >(l_read_2);
l_read_5.extractToRight< 0, ATTR_EC_GARD_LENGTH >(l_read_6);
l_read_scratch_reg.insertFromRight< ATTR_EQ_GARD_STARTBIT, ATTR_EQ_GARD_LENGTH >(l_read_2);
l_read_scratch_reg.insertFromRight< ATTR_EC_GARD_STARTBIT, ATTR_EC_GARD_LENGTH >(l_read_6);
FAPI_DBG("Setting up value of Scratch_reg1");
//Setting SCRATCH_REGISTER_1 register value
//CFAM.SCRATCH_REGISTER_1 = l_read_scratch_reg
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_1_FSI,
l_read_scratch_reg));
l_read_scratch8.setBit<0>();
}
//set_scratch2_reg
{
FAPI_DBG("Reading Scratch_reg2");
//Getting SCRATCH_REGISTER_2 register value
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_2_FSI,
l_read_scratch_reg)); //l_read_scratch_reg = CFAM.SCRATCH_REGISTER_2
FAPI_DBG("Reading ATTR_I2C_BUS_DIV_REF");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_I2C_BUS_DIV_REF, i_target_chip, l_read_4));
l_read_scratch_reg.insertFromRight< ATTR_I2C_BUS_DIV_REF_STARTBIT, ATTR_I2C_BUS_DIV_REF_LENGTH >(l_read_4);
FAPI_DBG("Setting up value of Scratch_reg2");
//Setting SCRATCH_REGISTER_2 register value
//CFAM.SCRATCH_REGISTER_2 = l_read_scratch_reg
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_2_FSI,
l_read_scratch_reg));
l_read_scratch8.setBit<1>();
}
//set_scratch3_reg
{
FAPI_DBG("Reading Scratch_reg3");
//Getting SCRATCH_REGISTER_3 register value
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_3_FSI,
l_read_scratch_reg)); //l_read_scratch_reg = CFAM.SCRATCH_REGISTER_3
FAPI_DBG("Reading the BOOT_FLAGS");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_BOOT_FLAGS, FAPI_SYSTEM, l_read_5));
l_read_scratch_reg.insertFromRight< ATTR_BOOT_FLAGS_STARTBIT, ATTR_BOOT_FLAGS_LENGTH >(l_read_5);
FAPI_DBG("Setting up value of Scratch_reg3");
//Setting SCRATCH_REGISTER_3 register value
//CFAM.SCRATCH_REGISTER_3 = l_read_scratch_reg
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_3_FSI,
l_read_scratch_reg));
l_read_scratch8.setBit<2>();
}
//set_scratch4_reg
{
FAPI_DBG("Reading Scratch_reg4");
//Getting SCRATCH_REGISTER_4 register value
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_4_FSI,
l_read_scratch_reg)); //l_read_scratch_reg = CFAM.SCRATCH_REGISTER_4
FAPI_DBG("Reading ATTR_BOOT_FREQ_MULT, ATTR_NEST_PLL_BUCKET");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_BOOT_FREQ_MULT, i_target_chip, l_read_4));
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_NEST_PLL_BUCKET, FAPI_SYSTEM, l_read_1));
l_read_scratch_reg.insertFromRight< ATTR_BOOT_FREQ_MULT_STARTBIT, ATTR_BOOT_FREQ_MULT_LENGTH >(l_read_4);
l_read_scratch_reg.insertFromRight< ATTR_NEST_PLL_BUCKET_STARTBIT, ATTR_NEST_PLL_BUCKET_LENGTH >(l_read_1);
FAPI_DBG("Setting up value of Scratch_reg4");
//Setting SCRATCH_REGISTER_4 register value
//CFAM.SCRATCH_REGISTER_4 = l_read_scratch_reg
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_4_FSI,
l_read_scratch_reg));
l_read_scratch8.setBit<3>();
}
//set_scratch5_reg
{
FAPI_DBG("Reading Scratch_reg5");
//Getting SCRATCH_REGISTER_5 register value
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_5_FSI,
l_read_scratch_reg)); //l_read_scratch_reg = CFAM.SCRATCH_REGISTER_5
FAPI_DBG("Reading the control flags : SYSTEM_IPL_PHASE, RISK_LEVEL, SYS_FORCE_ALL_CORES");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_IPL_PHASE, FAPI_SYSTEM, l_read_1));
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_RISK_LEVEL, FAPI_SYSTEM, l_read_2));
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYS_FORCE_ALL_CORES, FAPI_SYSTEM,
l_read_3));
l_read_scratch_reg.writeBit<0>(l_read_1.getBit<7>());
l_read_scratch_reg.writeBit<1>(l_read_3.getBit<7>());
l_read_scratch_reg.writeBit<2>(l_read_2.getBit<7>());
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_DISABLE_HBBL_VECTORS, FAPI_SYSTEM,
l_read_1));
l_read_scratch_reg.writeBit<3>(l_read_1.getBit<7>());
FAPI_DBG("Setting up value of Scratch_reg5");
//Setting SCRATCH_REGISTER_5 register value
//CFAM.SCRATCH_REGISTER_5 = l_read_scratch_reg
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_5_FSI,
l_read_scratch_reg));
l_read_scratch8.setBit<4>();
}
//set_scratch6_reg
{
FAPI_DBG("Reading Scratch_reg6");
//Getting SCRATCH_REGISTER_6 register value
FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_6_FSI,
l_read_scratch_reg)); //l_read_scratch_reg = CFAM.SCRATCH_REGISTER_6
FAPI_DBG("Reading attribute for Hostboot slave bit");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_SBE_MASTER_CHIP, i_target_chip,
l_read_1));
if ( l_read_1 )
{
l_read_scratch_reg.clearBit<24>();
}
else
{
l_read_scratch_reg.setBit<24>();
}
FAPI_DBG("Reading ATTR_PROC_FABRIC_GROUP and CHIP_ID");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_GROUP_ID, i_target_chip,
l_read_1));
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_CHIP_ID, i_target_chip,
l_read_2));
l_read_scratch_reg.insertFromRight< ATTR_PROC_FABRIC_GROUP_ID_STARTBIT, ATTR_PROC_FABRIC_GROUP_ID_LENGTH >(l_read_1);
l_read_scratch_reg.insertFromRight< ATTR_PROC_FABRIC_CHIP_ID_STARTBIT, ATTR_PROC_FABRIC_CHIP_ID_LENGTH >(l_read_2);
FAPI_DBG("Setting up value of Scratch_reg6");
//Setting SCRATCH_REGISTER_6 register value
//CFAM.SCRATCH_REGISTER_6 = l_read_scratch_reg
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_6_FSI,
l_read_scratch_reg));
l_read_scratch8.setBit<5>();
}
FAPI_DBG("Setting Scratch8 for validity of Scratch register");
//Setting SCRATCH_REGISTER_8 register value
//CFAM.SCRATCH_REGISTER_8 = l_read_scratch8
FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_SCRATCH_REGISTER_8_FSI,
l_read_scratch8));
FAPI_INF("Exiting ...");
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_xbus_enable_ridi.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,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_xbus_enable_ridi.H
///
/// @brief Enable RI/DI for XBUS
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Sunil kumar <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
#ifndef _P9_XBUS_ENABLE_RIDI_H_
#define _P9_XBUS_ENABLE_RIDI_H_
#include <fapi2.H>
typedef fapi2::ReturnCode (*p9_xbus_enable_ridi_FP_t)(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);
/// @brief Drop RI/DI for XBUS
///
/// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target
/// @return FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
fapi2::ReturnCode p9_xbus_enable_ridi(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);
}
#endif
<commit_msg>Update hardware procedure metadata<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_xbus_enable_ridi.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,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_xbus_enable_ridi.H
///
/// @brief Enable RI/DI for XBUS
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Sunil kumar <[email protected]>
// *HWP Team : Perv
// *HWP Level : 3
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
#ifndef _P9_XBUS_ENABLE_RIDI_H_
#define _P9_XBUS_ENABLE_RIDI_H_
#include <fapi2.H>
typedef fapi2::ReturnCode (*p9_xbus_enable_ridi_FP_t)(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);
/// @brief Drop RI/DI for XBUS
///
/// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target
/// @return FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
fapi2::ReturnCode p9_xbus_enable_ridi(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);
}
#endif
<|endoftext|> |
<commit_before>/* ConsoleWriter.cpp --
*
* Copyright (c) 2014, Lex Chou <lex at chou dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * 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 Swallow nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ConsoleWriter.h"
#include <stdlib.h>
#include <wchar.h>
#include <stdarg.h>
#include <string.h>
#if !defined(_WIN32) && !defined(WIN32)
#include <unistd.h>
#endif
#include <io.h>
#include <stdio.h>
void ConsoleWriter::printf(const wchar_t* fmt, ...)
{
va_list va;
va_start(va, fmt);
vwprintf(fmt, va);
va_end(va);
}
ConsoleWriter* ConsoleWriter::create()
{
if(isatty(fileno(stdout)))
{
return new AnsiConsoleWriter();
}
else
{
return new PlainConsoleWriter();
}
}
void PlainConsoleWriter::setForegroundColor(ConsoleColor color, ConsoleIntensity intensity)
{
}
void PlainConsoleWriter::setBackgroundColor(ConsoleColor color, ConsoleIntensity intensity)
{
}
void PlainConsoleWriter::reset()
{
}
void AnsiConsoleWriter::setForegroundColor(ConsoleColor color, ConsoleIntensity intensity)
{
printf(L"\x1b[%dm", (intensity == Normal ? 30 : 90) + color);
}
void AnsiConsoleWriter::setBackgroundColor(ConsoleColor color, ConsoleIntensity intensity)
{
printf(L"\x1b[%dm", (intensity == Normal ? 40 : 100) + color);
}
void AnsiConsoleWriter::reset()
{
printf(L"\x1b[0m");
}
<commit_msg>Disable ANSI escape codes on win32 platform<commit_after>/* ConsoleWriter.cpp --
*
* Copyright (c) 2014, Lex Chou <lex at chou dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * 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 Swallow nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ConsoleWriter.h"
#include <stdlib.h>
#include <wchar.h>
#include <stdarg.h>
#include <string.h>
#if !defined(_WIN32) && !defined(WIN32)
#include <unistd.h>
#else
#include <io.h>
#endif
#include <stdio.h>
void ConsoleWriter::printf(const wchar_t* fmt, ...)
{
va_list va;
va_start(va, fmt);
vwprintf(fmt, va);
va_end(va);
}
ConsoleWriter* ConsoleWriter::create()
{
#if !defined(_WIN32) && !defined(WIN32)
if(isatty(fileno(stdout)))
{
return new AnsiConsoleWriter();
}
else
{
return new PlainConsoleWriter();
}
#else
return new PlainConsoleWriter();
#endif
}
void PlainConsoleWriter::setForegroundColor(ConsoleColor color, ConsoleIntensity intensity)
{
}
void PlainConsoleWriter::setBackgroundColor(ConsoleColor color, ConsoleIntensity intensity)
{
}
void PlainConsoleWriter::reset()
{
}
void AnsiConsoleWriter::setForegroundColor(ConsoleColor color, ConsoleIntensity intensity)
{
printf(L"\x1b[%dm", (intensity == Normal ? 30 : 90) + color);
}
void AnsiConsoleWriter::setBackgroundColor(ConsoleColor color, ConsoleIntensity intensity)
{
printf(L"\x1b[%dm", (intensity == Normal ? 40 : 100) + color);
}
void AnsiConsoleWriter::reset()
{
printf(L"\x1b[0m");
}
<|endoftext|> |
<commit_before>#include <cstring>
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;
#include <arpa/inet.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include "socket.h"
// stdint.h is missing solaris 9-10 =[
#ifdef __sun
# include <inttypes.h>
#else
# include <stdint.h>
#endif
void Socket::IgnoreSIGPIPE()
{
::signal(SIGPIPE, SIG_IGN);
}
const int BUF_LENGTH = 1024;
Socket::Socket(const string& host, const uint16_t port) : fd(-1), ref(0)
{
Socket::IgnoreSIGPIPE();
sockaddr_in addr;
hostent *haddr = 0;
haddr = ::gethostbyname(host.c_str());
if (haddr == 0)
{
throw runtime_error(string("Socket error (resolve): ") + strerror(errno));
}
fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1)
{
throw runtime_error(string("Socket error (sock): ") + strerror(errno));
}
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);// Set the socket to async so that we can have a shorter timeout
memset((char*)&addr, 0, sizeof(addr));
memcpy(&addr.sin_addr.s_addr, haddr->h_addr, haddr->h_length);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (::connect(fd, (sockaddr*)&addr, sizeof(addr)) == -1 && errno != EINPROGRESS)
{
::close(fd);
throw runtime_error(string("Socket error (conn): ") + strerror(errno));
}
// Use a timeout of 2 seconds
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(fd, &fdset);
timeval timeout;
memset((char*)&timeout, 0, sizeof(timeout));
timeout.tv_sec = 2;
if (::select(fd + 1, 0, &fdset, 0, &timeout) == -1)
{
bool bad = true;
if (errno == EINPROGRESS)
{
int errc;
socklen_t len = sizeof(errc);
getsockopt(fd, SOL_SOCKET, SO_ERROR, &errc, &len);
if (errc == 0)
{
bad = false;
}
}
if (bad || errno == EINPROGRESS)
{
::close(fd);
throw runtime_error(string("Socket error (conn): ") + strerror(errno));
}
}
fcntl(fd, F_SETFL, flags);// unset the async socket
remote = host;
ref = new int(1);
}
Socket::Socket(int fdes, string Remote) : fd(fdes), ref(0), remote(Remote)
{
// cerr << "socket new : " << fd << endl;
ref = new int(1);
}
Socket::Socket(const Socket& rhs) : fd(rhs.fd), ref(rhs.ref), remote(rhs.remote)
{
// cerr << "socket copy: " << fd << endl;
++(*ref);
}
Socket& Socket::operator=(const Socket& rhs)
{
Socket::IgnoreSIGPIPE();
if (fd != -1)
{
--(*ref);
if (*ref <= 1)
{
delete ref;
::close(fd);
}
}
// cerr << "socket equa: " << fd << endl;
fd = rhs.fd;
ref = rhs.ref;
remote = rhs.remote;
++(*ref);
return *this;
}
Socket::~Socket()
{
--(*ref);
// cerr << "socket rem : " << fd << " " << *ref << endl;
if (*ref == 0)
{
delete ref;
// cerr << "socket disp: " << fd << " " << *ref << endl;
::close(fd);
}
}
void Socket::close(SocketEnd type)
{
if ((type & Read) == Read)
{
::shutdown(fd, SHUT_RD);
}
if ((type & Write) == Write)
{
::shutdown(fd, SHUT_WR);
}
}
string Socket::remoteHost() const
{
return remote;
}
string Socket::read(long size)
{
int recvChars, read = inBuffer.length();
char buffer[BUF_LENGTH];
string output;
if (size == -1 || size > (long)inBuffer.length())
{
do
{
recvChars = ::recv(fd, buffer, BUF_LENGTH, 0);
if (recvChars > 0)
{
read += recvChars;
inBuffer.append(buffer, recvChars);
}
}
while (recvChars >= 0 && read < size);
}
if (!inBuffer.empty() && recvChars == -1)
{
throw runtime_error(string("Socket error (read): ") + strerror(errno));
}
if (size > read)
{
output = inBuffer.substr(0, size);
inBuffer.erase(0, size);
}
else
{
output = inBuffer;
inBuffer.clear();
}
return output;
}
void Socket::write(const string& buffer)
{
if (::send(fd, buffer.data(), buffer.length(), 0) == -1)
{
throw runtime_error(string("Socket error (write): ") + strerror(errno));
}
}
ServerSocket::ServerSocket(const short port)
{
Socket::IgnoreSIGPIPE();
sockaddr_in addr;
fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1)
throw runtime_error(string("Socket error (sock): ") + strerror(errno));
memset((char*)&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
if (::bind(fd, (sockaddr*)&addr, sizeof(addr)) == -1)
throw runtime_error(string("Socket error (bind): ") + strerror(errno));
if (::listen(fd, 5) == -1)
throw runtime_error(string("Socket error (listen): ") + strerror(errno));
}
ServerSocket::~ServerSocket()
{
close(fd);
}
Socket ServerSocket::accept()
{
Socket::IgnoreSIGPIPE();
sockaddr_in in;
socklen_t len = sizeof(in);
int newSock = ::accept(fd, (sockaddr*)&in, &len);
if (newSock == -1)
throw runtime_error(string("Socket error (accept): ") + strerror(errno));
return Socket(newSock, inet_ntoa(in.sin_addr));
}
void ServerSocket::serveForever(void (*callback)(Socket sock))
{
while (true)
{
callback(accept());
}
}
<commit_msg>socket.cpp: remove ServerSocket.serveForever()<commit_after>#include <cstring>
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;
#include <arpa/inet.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include "socket.h"
// stdint.h is missing solaris 9-10 =[
#ifdef __sun
# include <inttypes.h>
#else
# include <stdint.h>
#endif
void Socket::IgnoreSIGPIPE()
{
::signal(SIGPIPE, SIG_IGN);
}
const int BUF_LENGTH = 1024;
Socket::Socket(const string& host, const uint16_t port) : fd(-1), ref(0)
{
Socket::IgnoreSIGPIPE();
sockaddr_in addr;
hostent *haddr = 0;
haddr = ::gethostbyname(host.c_str());
if (haddr == 0)
{
throw runtime_error(string("Socket error (resolve): ") + strerror(errno));
}
fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1)
{
throw runtime_error(string("Socket error (sock): ") + strerror(errno));
}
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);// Set the socket to async so that we can have a shorter timeout
memset((char*)&addr, 0, sizeof(addr));
memcpy(&addr.sin_addr.s_addr, haddr->h_addr, haddr->h_length);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (::connect(fd, (sockaddr*)&addr, sizeof(addr)) == -1 && errno != EINPROGRESS)
{
::close(fd);
throw runtime_error(string("Socket error (conn): ") + strerror(errno));
}
// Use a timeout of 2 seconds
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(fd, &fdset);
timeval timeout;
memset((char*)&timeout, 0, sizeof(timeout));
timeout.tv_sec = 2;
if (::select(fd + 1, 0, &fdset, 0, &timeout) == -1)
{
bool bad = true;
if (errno == EINPROGRESS)
{
int errc;
socklen_t len = sizeof(errc);
getsockopt(fd, SOL_SOCKET, SO_ERROR, &errc, &len);
if (errc == 0)
{
bad = false;
}
}
if (bad || errno == EINPROGRESS)
{
::close(fd);
throw runtime_error(string("Socket error (conn): ") + strerror(errno));
}
}
fcntl(fd, F_SETFL, flags);// unset the async socket
remote = host;
ref = new int(1);
}
Socket::Socket(int fdes, string Remote) : fd(fdes), ref(0), remote(Remote)
{
// cerr << "socket new : " << fd << endl;
ref = new int(1);
}
Socket::Socket(const Socket& rhs) : fd(rhs.fd), ref(rhs.ref), remote(rhs.remote)
{
// cerr << "socket copy: " << fd << endl;
++(*ref);
}
Socket& Socket::operator=(const Socket& rhs)
{
Socket::IgnoreSIGPIPE();
if (fd != -1)
{
--(*ref);
if (*ref <= 1)
{
delete ref;
::close(fd);
}
}
// cerr << "socket equa: " << fd << endl;
fd = rhs.fd;
ref = rhs.ref;
remote = rhs.remote;
++(*ref);
return *this;
}
Socket::~Socket()
{
--(*ref);
// cerr << "socket rem : " << fd << " " << *ref << endl;
if (*ref == 0)
{
delete ref;
// cerr << "socket disp: " << fd << " " << *ref << endl;
::close(fd);
}
}
void Socket::close(SocketEnd type)
{
if ((type & Read) == Read)
{
::shutdown(fd, SHUT_RD);
}
if ((type & Write) == Write)
{
::shutdown(fd, SHUT_WR);
}
}
string Socket::remoteHost() const
{
return remote;
}
string Socket::read(long size)
{
int recvChars, read = inBuffer.length();
char buffer[BUF_LENGTH];
string output;
if (size == -1 || size > (long)inBuffer.length())
{
do
{
recvChars = ::recv(fd, buffer, BUF_LENGTH, 0);
if (recvChars > 0)
{
read += recvChars;
inBuffer.append(buffer, recvChars);
}
}
while (recvChars >= 0 && read < size);
}
if (!inBuffer.empty() && recvChars == -1)
{
throw runtime_error(string("Socket error (read): ") + strerror(errno));
}
if (size > read)
{
output = inBuffer.substr(0, size);
inBuffer.erase(0, size);
}
else
{
output = inBuffer;
inBuffer.clear();
}
return output;
}
void Socket::write(const string& buffer)
{
if (::send(fd, buffer.data(), buffer.length(), 0) == -1)
{
throw runtime_error(string("Socket error (write): ") + strerror(errno));
}
}
ServerSocket::ServerSocket(const short port)
{
Socket::IgnoreSIGPIPE();
sockaddr_in addr;
fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1)
throw runtime_error(string("Socket error (sock): ") + strerror(errno));
memset((char*)&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
if (::bind(fd, (sockaddr*)&addr, sizeof(addr)) == -1)
throw runtime_error(string("Socket error (bind): ") + strerror(errno));
if (::listen(fd, 5) == -1)
throw runtime_error(string("Socket error (listen): ") + strerror(errno));
}
ServerSocket::~ServerSocket()
{
close(fd);
}
Socket ServerSocket::accept()
{
Socket::IgnoreSIGPIPE();
sockaddr_in in;
socklen_t len = sizeof(in);
int newSock = ::accept(fd, (sockaddr*)&in, &len);
if (newSock == -1)
throw runtime_error(string("Socket error (accept): ") + strerror(errno));
return Socket(newSock, inet_ntoa(in.sin_addr));
}
<|endoftext|> |
<commit_before>/* The libMesh Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* This library is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public */
/* License as published by the Free Software Foundation; either */
/* version 2.1 of the License, or (at your option) any later version. */
/* This library is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */
/* Lesser General Public License for more details. */
/* You should have received a copy of the GNU Lesser General Public */
/* License along with this library; if not, write to the Free Software */
/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
// <h1>Introduction Example 1 - Creation of a Mesh Object</h1>
//
// This is the first example program. It simply demonstrates
// how to create a mesh object. A mesh is read from file,
// information is printed to the screen, and the mesh is then
// written.
// C++ include files that we need
#include <iostream>
// Functions to initialize the library.
#include "libmesh/libmesh.h"
// Basic include files needed for the mesh functionality.
#include "libmesh/mesh.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
int main (int argc, char** argv)
{
// Initialize the library. This is necessary because the library
// may depend on a number of other libraries (i.e. MPI and PETSc)
// that require initialization before use. When the LibMeshInit
// object goes out of scope, other libraries and resources are
// finalized.
LibMeshInit init (argc, argv);
// Check for proper usage. The program is designed to be run
// as follows:
// ./ex1 -d DIM input_mesh_name [-o output_mesh_name]
// where [output_mesh_name] is an optional parameter giving
// a filename to write the mesh into.
if (argc < 4)
{
if (libMesh::processor_id() == 0)
std::cerr << "Usage: " << argv[0] << " -d 2 in.mesh [-o out.mesh]"
<< std::endl;
// This handy function will print the file name, line number,
// and then abort. Currently the library does not use C++
// exception handling.
libmesh_error();
}
// Get the dimensionality of the mesh from argv[2]
const unsigned int dim = std::atoi(argv[2]);
// Skip higher-dimensional examples on a lower-dimensional libMesh build
libmesh_example_assert(dim <= LIBMESH_DIM, "2D/3D support");
// Create a mesh, with dimension to be overridden later, on the
// default MPI communicator.
Mesh mesh(init.comm());
// We may need XDR support compiled in to read binary .xdr files
std::string input_filename = argv[3];
libmesh_example_assert(LIBMESH_HAVE_XDR ||
input_filename.rfind(".xdr") >=
input_filename.size(), "XDR support");
// Read the input mesh.
mesh.read (argv[3]);
// Print information about the mesh to the screen.
mesh.print_info();
// Write the output mesh if the user specified an
// output file name.
if (argc >= 6 && std::string("-o") == argv[4])
{
// We may need XDR support compiled in to read binary .xdr files
std::string output_filename = argv[5];
libmesh_example_assert(LIBMESH_HAVE_XDR ||
output_filename.rfind(".xdr") >=
output_filename.size(), "XDR support");
mesh.write (argv[5]);
}
// All done. libMesh objects are destroyed here. Because the
// LibMeshInit object was created first, its destruction occurs
// last, and it's destructor finalizes any external libraries and
// checks for leaked memory.
return 0;
}
<commit_msg>Fix for --disable-xdr<commit_after>/* The libMesh Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* This library is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public */
/* License as published by the Free Software Foundation; either */
/* version 2.1 of the License, or (at your option) any later version. */
/* This library is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */
/* Lesser General Public License for more details. */
/* You should have received a copy of the GNU Lesser General Public */
/* License along with this library; if not, write to the Free Software */
/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
// <h1>Introduction Example 1 - Creation of a Mesh Object</h1>
//
// This is the first example program. It simply demonstrates
// how to create a mesh object. A mesh is read from file,
// information is printed to the screen, and the mesh is then
// written.
// C++ include files that we need
#include <iostream>
// Functions to initialize the library.
#include "libmesh/libmesh.h"
// Basic include files needed for the mesh functionality.
#include "libmesh/mesh.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
int main (int argc, char** argv)
{
// Initialize the library. This is necessary because the library
// may depend on a number of other libraries (i.e. MPI and PETSc)
// that require initialization before use. When the LibMeshInit
// object goes out of scope, other libraries and resources are
// finalized.
LibMeshInit init (argc, argv);
// Check for proper usage. The program is designed to be run
// as follows:
// ./ex1 -d DIM input_mesh_name [-o output_mesh_name]
// where [output_mesh_name] is an optional parameter giving
// a filename to write the mesh into.
if (argc < 4)
{
if (libMesh::processor_id() == 0)
std::cerr << "Usage: " << argv[0] << " -d 2 in.mesh [-o out.mesh]"
<< std::endl;
// This handy function will print the file name, line number,
// and then abort. Currently the library does not use C++
// exception handling.
libmesh_error();
}
// Get the dimensionality of the mesh from argv[2]
const unsigned int dim = std::atoi(argv[2]);
// Skip higher-dimensional examples on a lower-dimensional libMesh build
libmesh_example_assert(dim <= LIBMESH_DIM, "2D/3D support");
// Create a mesh, with dimension to be overridden later, on the
// default MPI communicator.
Mesh mesh(init.comm());
// We may need XDR support compiled in to read binary .xdr files
std::string input_filename = argv[3];
#ifndef LIBMESH_HAVE_XDR
libmesh_example_assert(input_filename.rfind(".xdr") >=
input_filename.size(), "XDR support");
#endif
// Read the input mesh.
mesh.read (argv[3]);
// Print information about the mesh to the screen.
mesh.print_info();
// Write the output mesh if the user specified an
// output file name.
if (argc >= 6 && std::string("-o") == argv[4])
{
// We may need XDR support compiled in to read binary .xdr files
std::string output_filename = argv[5];
#ifndef LIBMESH_HAVE_XDR
libmesh_example_assert(output_filename.rfind(".xdr") >=
output_filename.size(), "XDR support");
#endif
mesh.write (argv[5]);
}
// All done. libMesh objects are destroyed here. Because the
// LibMeshInit object was created first, its destruction occurs
// last, and it's destructor finalizes any external libraries and
// checks for leaked memory.
return 0;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Library : Image Registration Toolkit (IRTK)
Module : $Id$
Copyright : Imperial College, Department of Computing
Visual Information Processing (VIP), 2008 onwards
Date : $Date$
Version : $Revision$
Changes : $Author$
=========================================================================*/
#include <irtkImage.h>
#include <irtkImageFunction.h>
#include <irtkHistogram.h>
#include <irtkTransformation.h>
// Default filenames
char *source_name = NULL, *target_name = NULL, *mask_name = NULL;
char *trans_name = NULL, *output_name = NULL;
#define DEFAULT_BINS 255
// Default number of bins
int nbins_x = 0, nbins_y = 0;
void usage()
{
cerr << "Usage: evaluation [target] [source] <options>\n" << endl;
cerr << "where <options> is one or more of the following: \n" << endl;
cerr << "<-dofin file> Input transformation" << endl;
cerr << "<-nbins_x no> Number of bins for target (Default smaller of dynamic range or 255)" << endl;
cerr << "<-nbins_y no> Number of bins for source (Default as above)" << endl;
cerr << "<-Rx1 pixel> Region of interest" << endl;
cerr << "<-Ry1 pixel> Region of interest" << endl;
cerr << "<-Rz1 pixel> Region of interest" << endl;
cerr << "<-Rx2 pixel> Region of interest" << endl;
cerr << "<-Ry2 pixel> Region of interest" << endl;
cerr << "<-Rz2 pixel> Region of interest" << endl;
cerr << "<-Tp value> Padding value in target" << endl;
cerr << "<-mask file> Binary mask to define ROI" << endl;
cerr << "<-linear> Linear interpolation" << endl;
cerr << "<-bspline> B-spline interpolation" << endl;
cerr << "<-cspline> Cubic spline interpolation" << endl;
cerr << "<-sinc> Sinc interpolation" << endl;
cerr << "<-output> Output similarity values to file" << endl;
exit(1);
}
int main(int argc, char **argv)
{
irtkTransformation *transformation = NULL;
irtkInterpolateImageFunction *interpolator = NULL;
irtkGreyPixel target_min, source_min, target_max, source_max;
int ok, i, x, y, z, i1, j1, k1, i2, j2, k2;
double x1, y1, z1, x2, y2, z2, Tp, widthx, widthy, val;
// Check command line
if (argc < 3) {
usage();
}
// Parse source and target images
target_name = argv[1];
argc--;
argv++;
source_name = argv[1];
argc--;
argv++;
// Read target and source image
irtkGreyImage target(target_name);
irtkGreyImage source(source_name);
// Default padding
Tp = -1.0 * FLT_MAX;
// Fix ROI
i1 = 0;
j1 = 0;
k1 = 0;
i2 = target.GetX();
j2 = target.GetY();
k2 = target.GetZ();
// Fix no. of bins;
nbins_x = 0;
nbins_y = 0;
while (argc > 1) {
ok = false;
if ((ok == false) && (strcmp(argv[1], "-dofin") == 0)) {
argc--;
argv++;
trans_name = argv[1];
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-nbins_x") == 0)) {
argc--;
argv++;
nbins_x = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-nbins_y") == 0)) {
argc--;
argv++;
nbins_y = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Tp") == 0)) {
argc--;
argv++;
Tp = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Rx1") == 0)) {
argc--;
argv++;
i1 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Rx2") == 0)) {
argc--;
argv++;
i2 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Ry1") == 0)) {
argc--;
argv++;
j1 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Ry2") == 0)) {
argc--;
argv++;
j2 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Rz1") == 0)) {
argc--;
argv++;
k1 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Rz2") == 0)) {
argc--;
argv++;
k2 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-linear") == 0)) {
argc--;
argv++;
if (source.GetZ() == 1){
interpolator = new irtkLinearInterpolateImageFunction2D;
} else {
interpolator = new irtkLinearInterpolateImageFunction;
}
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-bspline") == 0)) {
argc--;
argv++;
if (source.GetZ() == 1){
interpolator = new irtkBSplineInterpolateImageFunction2D;
} else {
interpolator = new irtkBSplineInterpolateImageFunction;
}
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-cspline") == 0)) {
argc--;
argv++;
if (source.GetZ() == 1){
interpolator = new irtkCSplineInterpolateImageFunction2D;
} else {
interpolator = new irtkCSplineInterpolateImageFunction;
}
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-sinc") == 0)) {
argc--;
argv++;
if (source.GetZ() == 1){
interpolator = new irtkSincInterpolateImageFunction2D;
} else {
interpolator = new irtkSincInterpolateImageFunction;
}
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-mask") == 0)) {
argc--;
argv++;
mask_name = argv[1];
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-output") == 0)) {
argc--;
argv++;
output_name = argv[1];
argc--;
argv++;
ok = true;
}
if (ok == false) {
cerr << "Can not parse argument " << argv[1] << endl;
usage();
}
}
irtkGreyImage mask;
// Set up a mask,
if (mask_name == NULL) {
mask.Read(target_name);
irtkGreyPixel *ptr2mask = mask.GetPointerToVoxels();
irtkGreyPixel *ptr2tgt = target.GetPointerToVoxels();
for (i = 0; i < target.GetNumberOfVoxels(); i++) {
if (*ptr2tgt > Tp)
*ptr2mask = 1;
else
*ptr2mask = 0;
++ptr2tgt;
++ptr2mask;
}
} else {
mask.Read(mask_name);
if ((mask.GetX() != target.GetX()) ||
(mask.GetY() != target.GetY()) ||
(mask.GetZ() != target.GetZ())) {
cerr << "evaluation2: Target and mask dimensions mismatch. Exiting." << endl;
exit(1);
}
}
// If there is an region of interest, use it
if ((i1 != 0) || (i2 != target.GetX()) ||
(j1 != 0) || (j2 != target.GetY()) ||
(k1 != 0) || (k2 != target.GetZ())) {
target = target.GetRegion(i1, j1, k1, i2, j2, k2);
source = source.GetRegion(i1, j1, k1, i2, j2, k2);
mask = mask.GetRegion(i1, j1, k1, i2, j2, k2);
}
// Set min and max of histogram
target.GetMinMax(&target_min, &target_max);
source.GetMinMax(&source_min, &source_max);
// Calculate number of bins to use
if (nbins_x == 0) {
nbins_x = (int) round(target_max - target_min) + 1;
if (nbins_x > DEFAULT_BINS)
nbins_x = DEFAULT_BINS;
}
if (nbins_y == 0) {
nbins_y = (int) round(source_max - source_min) + 1;
if (nbins_y > DEFAULT_BINS)
nbins_y = DEFAULT_BINS;
}
// Create default interpolator if necessary
if (interpolator == NULL) {
if (source.GetZ() == 1){
interpolator = new irtkNearestNeighborInterpolateImageFunction2D;
} else {
interpolator = new irtkNearestNeighborInterpolateImageFunction;
}
}
interpolator->SetInput(&source);
interpolator->Initialize();
// Calculate the source image domain in which we can interpolate
interpolator->Inside(x1, y1, z1, x2, y2, z2);
// Create histogram
irtkHistogram_2D<int> histogram(nbins_x, nbins_y);
widthx = (target_max - target_min) / (nbins_x - 1.0);
widthy = (source_max - source_min) / (nbins_y - 1.0);
histogram.PutMin(target_min - 0.5*widthx, source_min - 0.5*widthy);
histogram.PutMax(target_max + 0.5*widthx, source_max + 0.5*widthy);
if (trans_name == 0) {
transformation = new irtkRigidTransformation;
} else {
transformation = irtkTransformation::New(trans_name);
}
target_min = FLT_MAX;
source_min = FLT_MAX;
target_max = -1.0 * FLT_MAX;
source_max = -1.0 * FLT_MAX;
// Fill histogram
for (z = 0; z < target.GetZ(); z++) {
for (y = 0; y < target.GetY(); y++) {
for (x = 0; x < target.GetX(); x++) {
if (mask(x, y, z) > 0) {
val = target(x, y, z);
if (val > target_max)
target_max = val;
if (val < target_min)
target_min = val;
irtkPoint p(x, y, z);
// Transform point into world coordinates
target.ImageToWorld(p);
// Transform point
transformation->Transform(p);
// Transform point into image coordinates
source.WorldToImage(p);
// A bad thing might happen for the 2D case.
if ((source.GetZ() == 1) &&
(p._z > 0.5 || p._z < -0.5)){
cerr << "Transformed point outside plane of 2D source image." << endl;
exit(1);
}
// 2D and in plane but out of FoV.
if ((source.GetZ() == 1) &&
(p._x <= x1 || p._x >= x2 ||
p._y <= y1 || p._y >= y2))
continue;
// 3D and out of FoV.
if ((source.GetZ() > 1) &&
(p._x <= x1 || p._x >= x2 ||
p._y <= y1 || p._y >= y2 ||
p._z <= z1 || p._z >= z2))
continue;
// Should be able to interpolate if we've got this far.
val = interpolator->EvaluateInside(p._x, p._y, p._z);
histogram.AddSample(target(x, y, z), val);
if (val > source_max)
source_max = val;
if (val < source_min)
source_min = val;
}
}
}
}
cout << "SSD: " << histogram.SumsOfSquaredDifferences() / (double)histogram.NumberOfSamples() << endl;
cout << "CC: " << histogram.CrossCorrelation() << endl;
cout << "NMI: " << histogram.NormalizedMutualInformation() << endl;
if (nbins_x == nbins_y) {
cout << "Label consistency: " << histogram.LabelConsistency() << endl;
cout << "Kappa statistic: " << histogram.Kappa() << endl;
}
if(output_name){
cerr << "Writing Results of SSD CC and NMI to " << output_name << endl;
ofstream fout(output_name,ios::app);
fout << histogram.SumsOfSquaredDifferences() / (double)histogram.NumberOfSamples() <<endl;
fout << histogram.CrossCorrelation() <<endl;
fout << histogram.NormalizedMutualInformation() <<endl;
if (nbins_x == nbins_y) {
fout << histogram.LabelConsistency() << endl;
}
fout.close();
}
}
<commit_msg>padding for source image<commit_after>/*=========================================================================
Library : Image Registration Toolkit (IRTK)
Module : $Id$
Copyright : Imperial College, Department of Computing
Visual Information Processing (VIP), 2008 onwards
Date : $Date$
Version : $Revision$
Changes : $Author$
=========================================================================*/
#include <irtkImage.h>
#include <irtkImageFunction.h>
#include <irtkHistogram.h>
#include <irtkTransformation.h>
// Default filenames
char *source_name = NULL, *target_name = NULL, *mask_name = NULL;
char *trans_name = NULL, *output_name = NULL;
#define DEFAULT_BINS 255
// Default number of bins
int nbins_x = 0, nbins_y = 0;
void usage()
{
cerr << "Usage: evaluation [target] [source] <options>\n" << endl;
cerr << "where <options> is one or more of the following: \n" << endl;
cerr << "<-dofin file> Input transformation" << endl;
cerr << "<-nbins_x no> Number of bins for target (Default smaller of dynamic range or 255)" << endl;
cerr << "<-nbins_y no> Number of bins for source (Default as above)" << endl;
cerr << "<-Rx1 pixel> Region of interest" << endl;
cerr << "<-Ry1 pixel> Region of interest" << endl;
cerr << "<-Rz1 pixel> Region of interest" << endl;
cerr << "<-Rx2 pixel> Region of interest" << endl;
cerr << "<-Ry2 pixel> Region of interest" << endl;
cerr << "<-Rz2 pixel> Region of interest" << endl;
cerr << "<-Tp value> Padding value in target" << endl;
cerr << "<-mask file> Binary mask to define ROI" << endl;
cerr << "<-linear> Linear interpolation" << endl;
cerr << "<-bspline> B-spline interpolation" << endl;
cerr << "<-cspline> Cubic spline interpolation" << endl;
cerr << "<-sinc> Sinc interpolation" << endl;
cerr << "<-output> Output similarity values to file" << endl;
exit(1);
}
int main(int argc, char **argv)
{
irtkTransformation *transformation = NULL;
irtkInterpolateImageFunction *interpolator = NULL;
irtkGreyPixel target_min, source_min, target_max, source_max;
int ok, i, x, y, z, i1, j1, k1, i2, j2, k2;
double x1, y1, z1, x2, y2, z2, Tp, widthx, widthy, val;
// Check command line
if (argc < 3) {
usage();
}
// Parse source and target images
target_name = argv[1];
argc--;
argv++;
source_name = argv[1];
argc--;
argv++;
// Read target and source image
irtkGreyImage target(target_name);
irtkGreyImage source(source_name);
// Default padding
Tp = -1.0 * FLT_MAX;
// Fix ROI
i1 = 0;
j1 = 0;
k1 = 0;
i2 = target.GetX();
j2 = target.GetY();
k2 = target.GetZ();
// Fix no. of bins;
nbins_x = 0;
nbins_y = 0;
while (argc > 1) {
ok = false;
if ((ok == false) && (strcmp(argv[1], "-dofin") == 0)) {
argc--;
argv++;
trans_name = argv[1];
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-nbins_x") == 0)) {
argc--;
argv++;
nbins_x = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-nbins_y") == 0)) {
argc--;
argv++;
nbins_y = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Tp") == 0)) {
argc--;
argv++;
Tp = atof(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Rx1") == 0)) {
argc--;
argv++;
i1 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Rx2") == 0)) {
argc--;
argv++;
i2 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Ry1") == 0)) {
argc--;
argv++;
j1 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Ry2") == 0)) {
argc--;
argv++;
j2 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Rz1") == 0)) {
argc--;
argv++;
k1 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-Rz2") == 0)) {
argc--;
argv++;
k2 = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-linear") == 0)) {
argc--;
argv++;
if (source.GetZ() == 1){
interpolator = new irtkLinearInterpolateImageFunction2D;
} else {
interpolator = new irtkLinearInterpolateImageFunction;
}
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-bspline") == 0)) {
argc--;
argv++;
if (source.GetZ() == 1){
interpolator = new irtkBSplineInterpolateImageFunction2D;
} else {
interpolator = new irtkBSplineInterpolateImageFunction;
}
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-cspline") == 0)) {
argc--;
argv++;
if (source.GetZ() == 1){
interpolator = new irtkCSplineInterpolateImageFunction2D;
} else {
interpolator = new irtkCSplineInterpolateImageFunction;
}
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-sinc") == 0)) {
argc--;
argv++;
if (source.GetZ() == 1){
interpolator = new irtkSincInterpolateImageFunction2D;
} else {
interpolator = new irtkSincInterpolateImageFunction;
}
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-mask") == 0)) {
argc--;
argv++;
mask_name = argv[1];
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-output") == 0)) {
argc--;
argv++;
output_name = argv[1];
argc--;
argv++;
ok = true;
}
if (ok == false) {
cerr << "Can not parse argument " << argv[1] << endl;
usage();
}
}
irtkGreyImage mask;
// Set up a mask,
if (mask_name == NULL) {
mask.Read(target_name);
irtkGreyPixel *ptr2mask = mask.GetPointerToVoxels();
irtkGreyPixel *ptr2tgt = target.GetPointerToVoxels();
for (i = 0; i < target.GetNumberOfVoxels(); i++) {
if (*ptr2tgt > Tp)
*ptr2mask = 1;
else
*ptr2mask = 0;
++ptr2tgt;
++ptr2mask;
}
} else {
mask.Read(mask_name);
if ((mask.GetX() != target.GetX()) ||
(mask.GetY() != target.GetY()) ||
(mask.GetZ() != target.GetZ())) {
cerr << "evaluation2: Target and mask dimensions mismatch. Exiting." << endl;
exit(1);
}
}
// If there is an region of interest, use it
if ((i1 != 0) || (i2 != target.GetX()) ||
(j1 != 0) || (j2 != target.GetY()) ||
(k1 != 0) || (k2 != target.GetZ())) {
target = target.GetRegion(i1, j1, k1, i2, j2, k2);
source = source.GetRegion(i1, j1, k1, i2, j2, k2);
mask = mask.GetRegion(i1, j1, k1, i2, j2, k2);
}
// Set min and max of histogram
target.GetMinMax(&target_min, &target_max);
source.GetMinMax(&source_min, &source_max);
// Calculate number of bins to use
if (nbins_x == 0) {
nbins_x = (int) round(target_max - target_min) + 1;
if (nbins_x > DEFAULT_BINS)
nbins_x = DEFAULT_BINS;
}
if (nbins_y == 0) {
nbins_y = (int) round(source_max - source_min) + 1;
if (nbins_y > DEFAULT_BINS)
nbins_y = DEFAULT_BINS;
}
// Create default interpolator if necessary
if (interpolator == NULL) {
if (source.GetZ() == 1){
interpolator = new irtkNearestNeighborInterpolateImageFunction2D;
} else {
interpolator = new irtkNearestNeighborInterpolateImageFunction;
}
}
interpolator->SetInput(&source);
interpolator->Initialize();
// Calculate the source image domain in which we can interpolate
interpolator->Inside(x1, y1, z1, x2, y2, z2);
// Create histogram
irtkHistogram_2D<int> histogram(nbins_x, nbins_y);
widthx = (target_max - target_min) / (nbins_x - 1.0);
widthy = (source_max - source_min) / (nbins_y - 1.0);
histogram.PutMin(target_min - 0.5*widthx, source_min - 0.5*widthy);
histogram.PutMax(target_max + 0.5*widthx, source_max + 0.5*widthy);
if (trans_name == 0) {
transformation = new irtkRigidTransformation;
} else {
transformation = irtkTransformation::New(trans_name);
}
target_min = FLT_MAX;
source_min = FLT_MAX;
target_max = -1.0 * FLT_MAX;
source_max = -1.0 * FLT_MAX;
// Fill histogram
for (z = 0; z < target.GetZ(); z++) {
for (y = 0; y < target.GetY(); y++) {
for (x = 0; x < target.GetX(); x++) {
if (mask(x, y, z) > 0) {
val = target(x, y, z);
if (val > target_max)
target_max = val;
if (val < target_min)
target_min = val;
irtkPoint p(x, y, z);
// Transform point into world coordinates
target.ImageToWorld(p);
// Transform point
transformation->Transform(p);
// Transform point into image coordinates
source.WorldToImage(p);
// A bad thing might happen for the 2D case.
if ((source.GetZ() == 1) &&
(p._z > 0.5 || p._z < -0.5)){
cerr << "Transformed point outside plane of 2D source image." << endl;
exit(1);
}
// 2D and in plane but out of FoV.
if ((source.GetZ() == 1) &&
(p._x <= x1 || p._x >= x2 ||
p._y <= y1 || p._y >= y2))
continue;
// 3D and out of FoV.
if ((source.GetZ() > 1) &&
(p._x <= x1 || p._x >= x2 ||
p._y <= y1 || p._y >= y2 ||
p._z <= z1 || p._z >= z2))
continue;
// Should be able to interpolate if we've got this far.
val = interpolator->EvaluateInside(p._x, p._y, p._z);
if(val > Tp){
histogram.AddSample(target(x, y, z), val);
}
if (val > source_max)
source_max = val;
if (val < source_min)
source_min = val;
}
}
}
}
cout << "SSD: " << histogram.SumsOfSquaredDifferences() / (double)histogram.NumberOfSamples() << endl;
cout << "CC: " << histogram.CrossCorrelation() << endl;
cout << "NMI: " << histogram.NormalizedMutualInformation() << endl;
if (nbins_x == nbins_y) {
cout << "Label consistency: " << histogram.LabelConsistency() << endl;
cout << "Kappa statistic: " << histogram.Kappa() << endl;
}
if(output_name){
cerr << "Writing Results of SSD CC and NMI to " << output_name << endl;
ofstream fout(output_name,ios::app);
fout << histogram.SumsOfSquaredDifferences() / (double)histogram.NumberOfSamples() <<endl;
fout << histogram.CrossCorrelation() <<endl;
fout << histogram.NormalizedMutualInformation() <<endl;
if (nbins_x == nbins_y) {
fout << histogram.LabelConsistency() << endl;
}
fout.close();
}
}
<|endoftext|> |
<commit_before>/***************************************************
This is a library for the HDC1000 Humidity & Temp Sensor
Designed specifically to work with the HDC1008 sensor from Adafruit
----> https://www.adafruit.com/products/2635
These sensors use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
Modified for Photon needs application.h for types RMB
****************************************************/
#include "application.h"
#include "Adafruit_HDC1000/Adafruit_HDC1000.h"
Adafruit_HDC1000::Adafruit_HDC1000() {
}
boolean Adafruit_HDC1000::begin(uint8_t addr) {
_i2caddr = addr;
Wire.begin();
reset();
if (read16(HDC1000_MANUFID) != 0x5449) return false;
if (read16(HDC1000_DEVICEID) != 0x1000) return false;
return true;
}
void Adafruit_HDC1000::reset(void) {
// reset,combined temp/humidity measurement,and select 14 bit temp & humidity resolution
uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14;
Wire.beginTransmission(_i2caddr);
Wire.write(HDC1000_CONFIG); // set pointer register to configuration register RMB
Wire.write(config>>8); // now write out 2 bytes MSB first RMB
Wire.write(config&0xFF);
Wire.endTransmission();
delay(15);
}
float Adafruit_HDC1000::readTemperature(void) {
float temp = (read32(HDC1000_TEMP, 20) >> 16);
temp /= 65536;
temp *= 165;
temp -= 40;
return temp;
}
float Adafruit_HDC1000::readHumidity(void) {
// reads both temp and humidity, masks out temp in highest 16 bits
// originally used hum but humidity declared in private section of class
float humidity = (read32(HDC1000_TEMP, 20) & 0xFFFF);
humidity /= 65536;
humidity *= 100;
return hum;
}
// Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V
// Thanks to KFricke for micropython-hdc1008 on GitHub, usually called after Temp/Humid reading RMB
boolean Adafruit_HDC1000::batteryLOW(void) {
uint16_t battLOW = (read16(HDC1000_CONFIG_BATT, 20));
battLOW &= HDC1000_CONFIG_BATT; // mask off other bits, bit 11 will be 1 if voltage < 2.8V
if (battLOW> 0) return true;
return false;
}
/*********************************************************************/
uint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
delay(d);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);
uint16_t r = Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
uint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
// delay was hardcoded as 50, should be d (delay)
delay(d);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4);
uint32_t r = Wire.read();
// assembles temp into highest 16 bits, humidity into lowest 16 bits
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
<commit_msg>add ReadTempHumidity() function and getter func<commit_after>/***************************************************
This is a library for the HDC1000 Humidity & Temp Sensor
Designed specifically to work with the HDC1008 sensor from Adafruit
----> https://www.adafruit.com/products/2635
These sensors use I2C to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
Modified for Photon needs application.h for types RMB
****************************************************/
#include "application.h"
#include "Adafruit_HDC1000/Adafruit_HDC1000.h"
Adafruit_HDC1000::Adafruit_HDC1000() {
}
boolean Adafruit_HDC1000::begin(uint8_t addr) {
_i2caddr = addr;
Wire.begin();
reset();
if (read16(HDC1000_MANUFID) != 0x5449) return false;
if (read16(HDC1000_DEVICEID) != 0x1000) return false;
return true;
}
void Adafruit_HDC1000::reset(void) {
// reset,combined temp/humidity measurement,and select 14 bit temp & humidity resolution
uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14;
Wire.beginTransmission(_i2caddr);
Wire.write(HDC1000_CONFIG); // set pointer register to configuration register RMB
Wire.write(config>>8); // now write out 2 bytes MSB first RMB
Wire.write(config&0xFF);
Wire.endTransmission();
delay(15);
}
float Adafruit_HDC1000::readTemperature(void) {
float temp = (read32(HDC1000_TEMP, 20) >> 16);
temp /= 65536;
temp *= 165;
temp -= 40;
return temp;
}
float Adafruit_HDC1000::readHumidity(void) {
// reads both temp and humidity but masks out temp in highest 16 bits
// originally used hum but humidity declared in private section of class
float humidity = (read32(HDC1000_TEMP, 20) & 0xFFFF);
humidity /= 65536;
humidity *= 100;
return humidity;
}
void Adafruit_HDC1000::ReadTempHumidity(void) {
// HDC1008 setup to measure both temperature and humidity in one conversion
// this is a different way to access data in ONE read
// this sets internal private variables that can be accessed by Get() functions
uint32_t rt,rh ; // working variables
rt = read32(HDC1000_TEMP, 20); // get temp and humidity reading together
rh = rt; // save a copy for humidity processing
float temp = (rt >> 16); // convert to temp first
temp /= 65536;
temp *= 165;
temp -= 40;
float humidity = (rh & 0xFFFF); // now convert to humidity
humidity /= 65536;
humidity *= 100;
}
float Adafruit_HDC1000::GetTemperature(void) {
// getter function to access private temp variable
return temp ;
}
float Adafruit_HDC1000::GetHumidity(void) {
// getter function to access private humidity variable
return humidity ;
}
// Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V
// usually called after Temp/Humid reading RMB
// Thanks to KFricke for micropython-hdc1008 example on GitHub
boolean Adafruit_HDC1000::batteryLOW(void) {
uint16_t battLOW = (read16(HDC1000_CONFIG_BATT, 20));
battLOW &= HDC1000_CONFIG_BATT; // mask off other bits, bit 11 will be 1 if voltage < 2.8V
if (battLOW> 0) return true;
return false;
}
/*********************************************************************/
uint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
delay(d);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);
uint16_t r = Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
uint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) {
Wire.beginTransmission(_i2caddr);
Wire.write(a);
Wire.endTransmission();
// delay was hardcoded as 50, should use d RMB
delay(d);
Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4);
uint32_t r = Wire.read();
// assembles temp into highest 16 bits, humidity into lowest 16 bits
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
r <<= 8;
r |= Wire.read();
//Serial.println(r, HEX);
return r;
}
<|endoftext|> |
<commit_before>#ifndef ecmdSharedUtils_h
#define ecmdSharedUtils_h
// Copyright **********************************************************
//
// File ecmdSharedUtils.H
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 1996
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright ******************************************************
/* $Header$ */
/**
* @file ecmdSharedUtils.H
* @brief Useful functions for use throughout the ecmd C API and Plugin
*
*/
//--------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------
#include <string>
#include <vector>
#include <inttypes.h>
#include <ecmdDefines.H>
#include <ecmdDataBuffer.H>
#include <ecmdStructs.H>
//--------------------------------------------------------------------
// ENUM Definitions
//--------------------------------------------------------------------
/**
@brief Used by ecmdSetTargetDepth
*/
typedef enum {
ECMD_DEPTH_CAGE = 0,
ECMD_DEPTH_NODE,
ECMD_DEPTH_SLOT,
ECMD_DEPTH_CHIP,
ECMD_DEPTH_CHIPUNIT,
ECMD_DEPTH_THREAD,
ECMD_DEPTH_CORE // Re-added on 9/27/07 by JTA. We need both CORE and CHIPUNIT for ecmdSetTargetDepth
} ecmdTargetDepth_t;
//--------------------------------------------------------------------
// Forward References
//--------------------------------------------------------------------
/* The following two functions are overridden in ecmdClientPerlapi.H to remove io_argc */
#ifndef ECMD_PERLAPI
/** @name Command Line Parsing Functions */
//@{
/**
* @brief Iterates over argv, looking for given option string, removes it if found
* @retval 1 if option found, 0 otherwise
* @param io_argc Pointer to number of elements in io_argv array
* @param io_argv Array of strings passed in from command line
* @param i_option Option to look for
* @see ecmdParseOptionWithArgs
*/
bool ecmdParseOption (int * io_argc, char ** io_argv[], const char * i_option);
/**
* @brief Iterates over argv, looking for given option string, removes it if found
* @retval Value of option arg if found, NULL otherwise
* @param io_argc Pointer to number of elements in io_argv array
* @param io_argv Array of strings passed in from command line
* @param i_option Option to look for
* @see ecmdParseOptionWithArgs
*/
char * ecmdParseOptionWithArgs(int * io_argc, char ** io_argv[], const char * i_option);
//@}
#endif
/**
* @brief Breaks the string line into tokens based on all chars in seperators
* @param line String to tokenize
* @param seperators String of characters to use as seperators
* @param tokens Vector of strings that contain all the tokens
*/
void ecmdParseTokens(std::string line, const char* seperators, std::vector<std::string> & tokens);
/** @name Gen Functions */
//@{
/**
* @brief Turns the data in the buffer into ebcdic text
* @param i_data Data to convert
* @param start Bit to start at
* @param bitLen Number of bits
*/
std::string ecmdGenEbcdic(ecmdDataBuffer &i_data, int start, int bitLen);
/**
* @brief Default function for converting hex strings to unsigned int arrays
* @retval First element of the parsed data, or 0xFFFFFFFF if error
* @param o_numPtr The array that stores the data parsed from the input string
* @param i_hexChars input string of hex data- alignment stuff handled by Left and Right functions
* @param startPos
* @see ecmdGenB32FromHexRight
* @see ecmdGenB32FromHexLeft
*/
uint32_t ecmdGenB32FromHex(uint32_t * o_numPtr, const char * i_hexChars, int startPos);
/**
* @brief Convert a string of left-aligned Hex chars into a left-aligned unsigned int array
* @retval The first element of the parsed string data, or 0xFFFFFFFF if error
* @param o_numPtr The array that stores the data parsed from the input string
* @param i_hexChars A string of hex characters
* @see ecmdGenB32FromHexRight
* @see ecmdGenB32FromHex
*/
uint32_t ecmdGenB32FromHexLeft(uint32_t * o_numPtr, const char * i_hexChars);
/**
* @brief Convert a string of right-aligned Hex chars into a left-aligned unsigned int array
* @retval The first element of the parsed string data, or 0xFFFFFFFF if error
* @param o_numPtr The array that stores the data parsed from the input string
* @param i_hexChars A string of hex characters
* @param i_expectBits The number of defined bits in the o_numPtr array returned
* @see ecmdGenB32FromHex
* @see ecmdGenB32FromHexLeft
*/
uint32_t ecmdGenB32FromHexRight(uint32_t * o_numPtr, const char * i_hexChars, int i_expectBits = 0);
//@}
/**
* @brief Converts strings to unsigned int values. The input format is 0xABCDEF.
* @param i_str String in hexadecimal notation
* @date Tue Sep 21 13:22:33 2004
* @retval uint32_t value of converted input string
*/
uint32_t ecmdHexToUInt32(const char* i_str);
/**
* @brief Calculates a 32bit hash value for a given string.
*
* LICENSE:
* By Bob Jenkins, 1996. [email protected]. You may use this
* code any way you wish, private, educational, or commercial. It's free.
* See http://burtleburtle.net/bob/hash/doobs.html
*
* @param i_str String to convert to hash
* @param i_c Start value for hash.
* @retval Hash value
*/
uint32_t ecmdHashString32(const char *i_str, uint32_t i_c);
/**
* @brief Sets State Fields of Chip Target based on depth
* @param io_target an ecmdChipTarget struct representing a specific eCmd target
* @param i_depth an ecmdTargetDepth_t enum representing depth to be set valid
* @retval ECMD_SUCCESS if setting successful
* @retval ECMD_INVALID_ARGS if unsuccessful in finding a matching depth
* @post State Fields of Chip Target are set to either ECMD_TARGET_FIELD VALID or ECMD_TARGET_FIELD_UNUSED
TARGET DEPTH : Input To This Function
TARGET STATES : Gets Set By This Function
*/
uint32_t ecmdSetTargetDepth(ecmdChipTarget & io_target, ecmdTargetDepth_t i_depth);
/**
* @brief Sets Fields of ecmdMemoryEntry_t from the DCard data in the file
* @param i_filename file to read the d-card data from
* @param o_data list to be updated with the d-card data
* @retval ECMD_SUCCESS if setting successful
* @retval ECMD_INVALID_ARGS if unsuccessful in finding a matching depth
*/
uint32_t ecmdReadDcard(const char *i_filename, std::list<ecmdMemoryEntry> &o_data);
#endif /* ecmdSharedUtils_h */
// Change Log *********************************************************
//
// Flag Reason Vers Date Coder Description
// ---- -------- ---- -------- ----- -------------------------------
// cengel Initial Creation
// kloss added hash functions: hashString32, hexToUInt32
// baiocchi Added ecmdSetTargetDepth()
// End Change Log *****************************************************
<commit_msg>Fixed core/chipunit order since we have to re-release anyways<commit_after>#ifndef ecmdSharedUtils_h
#define ecmdSharedUtils_h
// Copyright **********************************************************
//
// File ecmdSharedUtils.H
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 1996
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright ******************************************************
/* $Header$ */
/**
* @file ecmdSharedUtils.H
* @brief Useful functions for use throughout the ecmd C API and Plugin
*
*/
//--------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------
#include <string>
#include <vector>
#include <inttypes.h>
#include <ecmdDefines.H>
#include <ecmdDataBuffer.H>
#include <ecmdStructs.H>
//--------------------------------------------------------------------
// ENUM Definitions
//--------------------------------------------------------------------
/**
@brief Used by ecmdSetTargetDepth
*/
typedef enum {
ECMD_DEPTH_CAGE = 0,
ECMD_DEPTH_NODE,
ECMD_DEPTH_SLOT,
ECMD_DEPTH_CHIP,
ECMD_DEPTH_CORE, // Re-added on 9/27/07 by JTA. We need both CORE and CHIPUNIT for ecmdSetTargetDepth
ECMD_DEPTH_CHIPUNIT,
ECMD_DEPTH_THREAD
} ecmdTargetDepth_t;
//--------------------------------------------------------------------
// Forward References
//--------------------------------------------------------------------
/* The following two functions are overridden in ecmdClientPerlapi.H to remove io_argc */
#ifndef ECMD_PERLAPI
/** @name Command Line Parsing Functions */
//@{
/**
* @brief Iterates over argv, looking for given option string, removes it if found
* @retval 1 if option found, 0 otherwise
* @param io_argc Pointer to number of elements in io_argv array
* @param io_argv Array of strings passed in from command line
* @param i_option Option to look for
* @see ecmdParseOptionWithArgs
*/
bool ecmdParseOption (int * io_argc, char ** io_argv[], const char * i_option);
/**
* @brief Iterates over argv, looking for given option string, removes it if found
* @retval Value of option arg if found, NULL otherwise
* @param io_argc Pointer to number of elements in io_argv array
* @param io_argv Array of strings passed in from command line
* @param i_option Option to look for
* @see ecmdParseOptionWithArgs
*/
char * ecmdParseOptionWithArgs(int * io_argc, char ** io_argv[], const char * i_option);
//@}
#endif
/**
* @brief Breaks the string line into tokens based on all chars in seperators
* @param line String to tokenize
* @param seperators String of characters to use as seperators
* @param tokens Vector of strings that contain all the tokens
*/
void ecmdParseTokens(std::string line, const char* seperators, std::vector<std::string> & tokens);
/** @name Gen Functions */
//@{
/**
* @brief Turns the data in the buffer into ebcdic text
* @param i_data Data to convert
* @param start Bit to start at
* @param bitLen Number of bits
*/
std::string ecmdGenEbcdic(ecmdDataBuffer &i_data, int start, int bitLen);
/**
* @brief Default function for converting hex strings to unsigned int arrays
* @retval First element of the parsed data, or 0xFFFFFFFF if error
* @param o_numPtr The array that stores the data parsed from the input string
* @param i_hexChars input string of hex data- alignment stuff handled by Left and Right functions
* @param startPos
* @see ecmdGenB32FromHexRight
* @see ecmdGenB32FromHexLeft
*/
uint32_t ecmdGenB32FromHex(uint32_t * o_numPtr, const char * i_hexChars, int startPos);
/**
* @brief Convert a string of left-aligned Hex chars into a left-aligned unsigned int array
* @retval The first element of the parsed string data, or 0xFFFFFFFF if error
* @param o_numPtr The array that stores the data parsed from the input string
* @param i_hexChars A string of hex characters
* @see ecmdGenB32FromHexRight
* @see ecmdGenB32FromHex
*/
uint32_t ecmdGenB32FromHexLeft(uint32_t * o_numPtr, const char * i_hexChars);
/**
* @brief Convert a string of right-aligned Hex chars into a left-aligned unsigned int array
* @retval The first element of the parsed string data, or 0xFFFFFFFF if error
* @param o_numPtr The array that stores the data parsed from the input string
* @param i_hexChars A string of hex characters
* @param i_expectBits The number of defined bits in the o_numPtr array returned
* @see ecmdGenB32FromHex
* @see ecmdGenB32FromHexLeft
*/
uint32_t ecmdGenB32FromHexRight(uint32_t * o_numPtr, const char * i_hexChars, int i_expectBits = 0);
//@}
/**
* @brief Converts strings to unsigned int values. The input format is 0xABCDEF.
* @param i_str String in hexadecimal notation
* @date Tue Sep 21 13:22:33 2004
* @retval uint32_t value of converted input string
*/
uint32_t ecmdHexToUInt32(const char* i_str);
/**
* @brief Calculates a 32bit hash value for a given string.
*
* LICENSE:
* By Bob Jenkins, 1996. [email protected]. You may use this
* code any way you wish, private, educational, or commercial. It's free.
* See http://burtleburtle.net/bob/hash/doobs.html
*
* @param i_str String to convert to hash
* @param i_c Start value for hash.
* @retval Hash value
*/
uint32_t ecmdHashString32(const char *i_str, uint32_t i_c);
/**
* @brief Sets State Fields of Chip Target based on depth
* @param io_target an ecmdChipTarget struct representing a specific eCmd target
* @param i_depth an ecmdTargetDepth_t enum representing depth to be set valid
* @retval ECMD_SUCCESS if setting successful
* @retval ECMD_INVALID_ARGS if unsuccessful in finding a matching depth
* @post State Fields of Chip Target are set to either ECMD_TARGET_FIELD VALID or ECMD_TARGET_FIELD_UNUSED
TARGET DEPTH : Input To This Function
TARGET STATES : Gets Set By This Function
*/
uint32_t ecmdSetTargetDepth(ecmdChipTarget & io_target, ecmdTargetDepth_t i_depth);
/**
* @brief Sets Fields of ecmdMemoryEntry_t from the DCard data in the file
* @param i_filename file to read the d-card data from
* @param o_data list to be updated with the d-card data
* @retval ECMD_SUCCESS if setting successful
* @retval ECMD_INVALID_ARGS if unsuccessful in finding a matching depth
*/
uint32_t ecmdReadDcard(const char *i_filename, std::list<ecmdMemoryEntry> &o_data);
#endif /* ecmdSharedUtils_h */
// Change Log *********************************************************
//
// Flag Reason Vers Date Coder Description
// ---- -------- ---- -------- ----- -------------------------------
// cengel Initial Creation
// kloss added hash functions: hashString32, hexToUInt32
// baiocchi Added ecmdSetTargetDepth()
// End Change Log *****************************************************
<|endoftext|> |
<commit_before>#include <cmath>
#include <numeric>
#include "control_loop.h"
#include "SystemState.h"
namespace hardware {
WORKING_AREA(ControlLoop::waControlThread, 4096);
Thread * ControlLoop::tp_control_ = 0;
ControlLoop::ControlLoop()
: startup_{false}, front_wheel_encoder_{STM32_TIM4, 800}
{
front_wheel_encoder_.set_count(0);
STM32_TIM5->CNT = 0;
}
// Caller: shell thread
msg_t ControlLoop::start(const char * filename)
{
tp_control_ = chThdCreateStatic(waControlThread,
sizeof(waControlThread),
chThdGetPriority() + 3,
ControlLoop::thread_function,
const_cast<char *>(filename));
if (!tp_control_)
return 1;
return 0;
}
// Caller: shell thread
msg_t ControlLoop::stop()
{
chThdTerminate(tp_control_);
msg_t m = chThdWait(tp_control_);
tp_control_ = 0;
return m;
}
// Caller: shell thread
void ControlLoop::shell_command(BaseSequentialStream *chp, int argc, char *argv[])
{
if (argc > 1 || argc < 0) {
chprintf(chp, "Invalid usage.\r\n");
return;
}
msg_t m;
if (tp_control_) { // control thread is running
m = stop();
if (argc == 0) {
chprintf(chp, "Data collection and control terminated with %d errors.\r\n", m);
return;
}
} else { // control thread is not running
if (argc == 0)
m = start("samples.dat");
else
m = start(argv[0]);
if (m == 0) {
chprintf(chp, "Data collection and control initiated.\r\n");
return;
}
}
chprintf(chp, "Errors starting threads with error: %d.\r\n", m);
}
// Caller: initially called by OS when thread is created.
// This is the highest priority thread
msg_t ControlLoop::thread_function(void * arg)
{
chRegSetThreadName("control");
ControlLoop loop;
return loop.exec(static_cast<const char *>(const_cast<const void *>(arg)));
}
void ControlLoop::set_gyro_lean(Sample& s)
{
s.has_gyro_lean = true;
static std::array<float, 100> lean_array {{}};
static int lean_i = 0;
static uint32_t system_time_prev = 0;
// first pass, use static lean value
s.gyro_lean.startup = startup_;
if (startup_) {
float ax = s.mpu6050.accelerometer_x;
float ay = s.mpu6050.accelerometer_y;
float az = s.mpu6050.accelerometer_z;
float accel_mag = std::sqrt(ax*ax + ay*ay + az*az);
float lean_static = std::asin(ax / accel_mag);
lean_array[lean_i] = lean_static;
lean_i = (lean_i + 1) % lean_array.size();
// after lean_array.size() samples, set the average value
if (lean_i == 0) {
float lean_avg = (std::accumulate(lean_array.begin(),
lean_array.end(), 0.0f) /
lean_array.size());
lean_array[0] = lean_avg;
s.gyro_lean.angle = lean_avg;
startup_ = false;
} else {
s.gyro_lean.angle = lean_static;
}
system_time_prev = s.system_time;
return;
}
// after setting average static lean, use gyro lean
float gyro_lean;
float dt = ((s.system_time - system_time_prev) *
constants::system_timer_seconds_per_count);
gyro_lean = lean_array[0] + s.mpu6050.gyroscope_y * dt;
lean_array[0] = gyro_lean;
s.gyro_lean.angle = gyro_lean;
system_time_prev = s.system_time;
return;
}
// Caller: Control thread
msg_t ControlLoop::exec(const char * file_name)
{
logging::SampleBuffer sample_buffer(file_name);
Sample s;
memset(&s, 0, sizeof(s));
systime_t time = chTimeNow(); // Initial time
systime_t sleep_time;
for (uint32_t i = 0; !chThdShouldTerminate(); ++i) {
time += MS2ST(constants::loop_period_ms); // Next deadline
// Begin pre control data collection
s.system_time = STM32_TIM5->CNT;
s.loop_count = i;
imu_.acquire_data(s);
s.encoder.front_wheel = front_wheel_encoder_.get_angle();
s.system_state |= systemstate::CollectionEnabled;
set_gyro_lean(s);
// End pre control data collection
// Begin control
rear_motor_controller_.update(s); // must be called prior to fork update since
fork_motor_controller_.update(s); // rear wheel rate is needed for gain scheduling
// End control
// Put the sample in to the buffer
bool encode_failure = !sample_buffer.insert(s);
// Illuminate the lean and steer LED's based on latest sample
illuminate_lean_steer(s);
// Clear the sample for the next iteration
// The first time through the loop, computation_time will be logged as zero,
// subsequent times will be accurate but delayed by one sample period. This
// is done to ensure that encoding computation is part of timing
// measurement.
uint32_t ti = s.system_time;
memset(&s, 0, sizeof(s));
s.computation_time = STM32_TIM5->CNT - ti;
// Similarly, encode failures will be delayed by one sample.
if (encode_failure)
s.system_state |= systemstate::SampleBufferEncodeError;
// set hardware button set
if (hw_button_enabled())
s.system_state |= systemstate::HWButton;
// Go to sleep until next interval
chSysLock();
sleep_time = time - chTimeNow();
if (static_cast<int32_t>(sleep_time) > 0)
chThdSleepS(sleep_time);
chSysUnlock();
} // for
return sample_buffer.flush_and_close();
}
}
<commit_msg>Fix startup_ initial value.<commit_after>#include <cmath>
#include <numeric>
#include "control_loop.h"
#include "SystemState.h"
namespace hardware {
WORKING_AREA(ControlLoop::waControlThread, 4096);
Thread * ControlLoop::tp_control_ = 0;
ControlLoop::ControlLoop()
: startup_{true}, front_wheel_encoder_{STM32_TIM4, 800}
{
front_wheel_encoder_.set_count(0);
STM32_TIM5->CNT = 0;
}
// Caller: shell thread
msg_t ControlLoop::start(const char * filename)
{
tp_control_ = chThdCreateStatic(waControlThread,
sizeof(waControlThread),
chThdGetPriority() + 3,
ControlLoop::thread_function,
const_cast<char *>(filename));
if (!tp_control_)
return 1;
return 0;
}
// Caller: shell thread
msg_t ControlLoop::stop()
{
chThdTerminate(tp_control_);
msg_t m = chThdWait(tp_control_);
tp_control_ = 0;
return m;
}
// Caller: shell thread
void ControlLoop::shell_command(BaseSequentialStream *chp, int argc, char *argv[])
{
if (argc > 1 || argc < 0) {
chprintf(chp, "Invalid usage.\r\n");
return;
}
msg_t m;
if (tp_control_) { // control thread is running
m = stop();
if (argc == 0) {
chprintf(chp, "Data collection and control terminated with %d errors.\r\n", m);
return;
}
} else { // control thread is not running
if (argc == 0)
m = start("samples.dat");
else
m = start(argv[0]);
if (m == 0) {
chprintf(chp, "Data collection and control initiated.\r\n");
return;
}
}
chprintf(chp, "Errors starting threads with error: %d.\r\n", m);
}
// Caller: initially called by OS when thread is created.
// This is the highest priority thread
msg_t ControlLoop::thread_function(void * arg)
{
chRegSetThreadName("control");
ControlLoop loop;
return loop.exec(static_cast<const char *>(const_cast<const void *>(arg)));
}
void ControlLoop::set_gyro_lean(Sample& s)
{
s.has_gyro_lean = true;
static std::array<float, 100> lean_array {{}};
static int lean_i = 0;
static uint32_t system_time_prev = 0;
// first pass, use static lean value
s.gyro_lean.startup = startup_;
if (startup_) {
float ax = s.mpu6050.accelerometer_x;
float ay = s.mpu6050.accelerometer_y;
float az = s.mpu6050.accelerometer_z;
float accel_mag = std::sqrt(ax*ax + ay*ay + az*az);
float lean_static = std::asin(ax / accel_mag);
lean_array[lean_i] = lean_static;
lean_i = (lean_i + 1) % lean_array.size();
// after lean_array.size() samples, set the average value
if (lean_i == 0) {
float lean_avg = (std::accumulate(lean_array.begin(),
lean_array.end(), 0.0f) /
lean_array.size());
lean_array[0] = lean_avg;
s.gyro_lean.angle = lean_avg;
startup_ = false;
} else {
s.gyro_lean.angle = lean_static;
}
system_time_prev = s.system_time;
return;
}
// after setting average static lean, use gyro lean
float gyro_lean;
float dt = ((s.system_time - system_time_prev) *
constants::system_timer_seconds_per_count);
gyro_lean = lean_array[0] + s.mpu6050.gyroscope_y * dt;
lean_array[0] = gyro_lean;
s.gyro_lean.angle = gyro_lean;
system_time_prev = s.system_time;
return;
}
// Caller: Control thread
msg_t ControlLoop::exec(const char * file_name)
{
logging::SampleBuffer sample_buffer(file_name);
Sample s;
memset(&s, 0, sizeof(s));
systime_t time = chTimeNow(); // Initial time
systime_t sleep_time;
for (uint32_t i = 0; !chThdShouldTerminate(); ++i) {
time += MS2ST(constants::loop_period_ms); // Next deadline
// Begin pre control data collection
s.system_time = STM32_TIM5->CNT;
s.loop_count = i;
imu_.acquire_data(s);
s.encoder.front_wheel = front_wheel_encoder_.get_angle();
s.system_state |= systemstate::CollectionEnabled;
set_gyro_lean(s);
// End pre control data collection
// Begin control
rear_motor_controller_.update(s); // must be called prior to fork update since
fork_motor_controller_.update(s); // rear wheel rate is needed for gain scheduling
// End control
// Put the sample in to the buffer
bool encode_failure = !sample_buffer.insert(s);
// Illuminate the lean and steer LED's based on latest sample
illuminate_lean_steer(s);
// Clear the sample for the next iteration
// The first time through the loop, computation_time will be logged as zero,
// subsequent times will be accurate but delayed by one sample period. This
// is done to ensure that encoding computation is part of timing
// measurement.
uint32_t ti = s.system_time;
memset(&s, 0, sizeof(s));
s.computation_time = STM32_TIM5->CNT - ti;
// Similarly, encode failures will be delayed by one sample.
if (encode_failure)
s.system_state |= systemstate::SampleBufferEncodeError;
// set hardware button set
if (hw_button_enabled())
s.system_state |= systemstate::HWButton;
// Go to sleep until next interval
chSysLock();
sleep_time = time - chTimeNow();
if (static_cast<int32_t>(sleep_time) > 0)
chThdSleepS(sleep_time);
chSysUnlock();
} // for
return sample_buffer.flush_and_close();
}
}
<|endoftext|> |
<commit_before>/*
* ______ __ __ __
* /\ _ \ __ /\ \/\ \ /\ \__
* \ \ \L\ \ __ __ /\_\ \_\ \ \ \____ ___\ \ ,_\ ____
* \ \ __ \/\ \/\ \\/\ \ /'_` \ \ '__`\ / __`\ \ \/ /',__\
* \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\
* \ \_\ \_\ \___/ \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/
* \/_/\/_/\/__/ \/_/\/__,_ /\/___/ \/___/ \/__/\/___/
* @copyright Copyright 2017 Avidbots Corp.
* @name world.cpp
* @brief Loads world file
* @author Joseph Duchesne
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, Avidbots Corp.
* 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 Avidbots Corp. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <Box2D/Box2D.h>
#include <flatland_server/debug_visualization.h>
#include <flatland_server/exceptions.h>
#include <flatland_server/world.h>
#include <ros/ros.h>
#include <yaml-cpp/yaml.h>
#include <boost/filesystem.hpp>
#include <map>
#include <string>
namespace flatland_server {
World::World() : gravity_(0, 0) { physics_world_ = new b2World(gravity_); }
World::~World() {
for (int i = 0; i < layers_.size(); i++) {
delete layers_[i];
}
delete physics_world_;
}
World *World::MakeWorld(const std::string &yaml_path) {
// parse the world YAML file
YAML::Node yaml;
try {
yaml = YAML::LoadFile(yaml_path);
} catch (const YAML::Exception &e) {
throw YAMLException("Error loading " + yaml_path, e);
}
if (yaml["properties"] && yaml["properties"].IsMap()) {
// TODO (Chunshang): parse properties
} else {
throw YAMLException("Missing/invalid world param \"properties\"");
}
World *w = new World();
try {
w->LoadLayers(yaml_path);
w->LoadModels(yaml_path);
} catch (const YAML::Exception &e) {
throw YAMLException(e);
}
return w;
}
void World::LoadLayers(const std::string &yaml_path) {
boost::filesystem::path path(yaml_path);
YAML::Node yaml;
try {
yaml = YAML::LoadFile(path.string());
} catch (const YAML::Exception &e) {
throw YAMLException("Error loading " + path.string(), e);
}
if (!yaml["layers"] || !yaml["layers"].IsSequence()) {
throw YAMLException("Missing/invalid world param \"layers\"");
}
// loop through each layer and parse the data
for (int i = 0; i < yaml["layers"].size(); i++) {
Layer *layer;
if (cfr_.IsLayersFull()) {
throw YAMLException("Max number of layers reached, max is " +
cfr_.MAX_LAYERS);
}
layer = Layer::MakeLayer(physics_world_, &cfr_, path.parent_path(),
yaml["layers"][i]);
layers_.push_back(layer);
ROS_INFO_NAMED("Layer", "Layer %s loaded", layer->name_.c_str());
}
}
void World::LoadModels(const std::string &yaml_path) {
boost::filesystem::path path(yaml_path);
YAML::Node yaml;
try {
yaml = YAML::LoadFile(path.string());
} catch (const YAML::Exception &e) {
throw YAMLException("Error loading " + path.string(), e);
}
// models is optional
if (yaml["models"] && !yaml["models"].IsSequence()) {
throw YAMLException("Invalid world param \"layers\", must be a sequence");
} else if (yaml["models"]) {
for (int i = 0; i < yaml["models"].size(); i++) {
boost::filesystem::path model_path(yaml["models"][i].as<std::string>());
if (model_path.string().front() != '/') {
model_path = path.parent_path() / model_path;
}
LoadModel(model_path);
}
}
}
void World::LoadModel(const boost::filesystem::path &model_yaml_path) {
YAML::Node n;
try {
n = YAML::LoadFile(model_yaml_path.string());
} catch (const YAML::Exception &e) {
throw YAMLException("Error loading " + model_yaml_path.string(), e);
}
Model *model = Model::MakeModel(physics_world_, &cfr_, model_yaml_path, n);
models_.push_back(model);
}
void World::DebugVisualize() {
for (auto &layer : layers_) {
DebugVisualization::get().Visualize(
std::string("layer_") + layer->name_, layer->body_->physics_body_,
layer->body_->color_[0], layer->body_->color_[1],
layer->body_->color_[2], layer->body_->color_[3]);
}
}
}; // namespace flatland_server
<commit_msg>clang format<commit_after>/*
* ______ __ __ __
* /\ _ \ __ /\ \/\ \ /\ \__
* \ \ \L\ \ __ __ /\_\ \_\ \ \ \____ ___\ \ ,_\ ____
* \ \ __ \/\ \/\ \\/\ \ /'_` \ \ '__`\ / __`\ \ \/ /',__\
* \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\
* \ \_\ \_\ \___/ \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/
* \/_/\/_/\/__/ \/_/\/__,_ /\/___/ \/___/ \/__/\/___/
* @copyright Copyright 2017 Avidbots Corp.
* @name world.cpp
* @brief Loads world file
* @author Joseph Duchesne
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, Avidbots Corp.
* 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 Avidbots Corp. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <Box2D/Box2D.h>
#include <flatland_server/debug_visualization.h>
#include <flatland_server/exceptions.h>
#include <flatland_server/world.h>
#include <ros/ros.h>
#include <yaml-cpp/yaml.h>
#include <boost/filesystem.hpp>
#include <map>
#include <string>
namespace flatland_server {
World::World() : gravity_(0, 0) { physics_world_ = new b2World(gravity_); }
World::~World() {
for (int i = 0; i < layers_.size(); i++) {
delete layers_[i];
}
delete physics_world_;
}
World *World::MakeWorld(const std::string &yaml_path) {
// parse the world YAML file
YAML::Node yaml;
try {
yaml = YAML::LoadFile(yaml_path);
} catch (const YAML::Exception &e) {
throw YAMLException("Error loading " + yaml_path, e);
}
if (yaml["properties"] && yaml["properties"].IsMap()) {
// TODO (Chunshang): parse properties
} else {
throw YAMLException("Missing/invalid world param \"properties\"");
}
World *w = new World();
try {
w->LoadLayers(yaml_path);
w->LoadModels(yaml_path);
} catch (const YAML::Exception &e) {
throw YAMLException(e);
}
return w;
}
void World::LoadLayers(const std::string &yaml_path) {
boost::filesystem::path path(yaml_path);
YAML::Node yaml;
try {
yaml = YAML::LoadFile(path.string());
} catch (const YAML::Exception &e) {
throw YAMLException("Error loading " + path.string(), e);
}
if (!yaml["layers"] || !yaml["layers"].IsSequence()) {
throw YAMLException("Missing/invalid world param \"layers\"");
}
// loop through each layer and parse the data
for (int i = 0; i < yaml["layers"].size(); i++) {
Layer *layer;
if (cfr_.IsLayersFull()) {
throw YAMLException("Max number of layers reached, max is " +
cfr_.MAX_LAYERS);
}
layer = Layer::MakeLayer(physics_world_, &cfr_, path.parent_path(),
yaml["layers"][i]);
layers_.push_back(layer);
ROS_INFO_NAMED("Layer", "Layer %s loaded", layer->name_.c_str());
}
}
void World::LoadModels(const std::string &yaml_path) {
boost::filesystem::path path(yaml_path);
YAML::Node yaml;
try {
yaml = YAML::LoadFile(path.string());
} catch (const YAML::Exception &e) {
throw YAMLException("Error loading " + path.string(), e);
}
// models is optional
if (yaml["models"] && !yaml["models"].IsSequence()) {
throw YAMLException("Invalid world param \"layers\", must be a sequence");
} else if (yaml["models"]) {
for (int i = 0; i < yaml["models"].size(); i++) {
boost::filesystem::path model_path(yaml["models"][i].as<std::string>());
if (model_path.string().front() != '/') {
model_path = path.parent_path() / model_path;
}
LoadModel(model_path);
}
}
}
void World::LoadModel(const boost::filesystem::path &model_yaml_path) {
YAML::Node n;
try {
n = YAML::LoadFile(model_yaml_path.string());
} catch (const YAML::Exception &e) {
throw YAMLException("Error loading " + model_yaml_path.string(), e);
}
Model *model = Model::MakeModel(physics_world_, &cfr_, model_yaml_path, n);
models_.push_back(model);
}
void World::DebugVisualize() {
for (auto &layer : layers_) {
DebugVisualization::get().Visualize(
std::string("layer_") + layer->name_, layer->body_->physics_body_,
layer->body_->color_[0], layer->body_->color_[1],
layer->body_->color_[2], layer->body_->color_[3]);
}
}
}; // namespace flatland_server
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/sax/SAXParseException.hpp>
#include "DOMTreeErrorReporter.hpp"
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
void DOMTreeErrorReporter::warning(const SAXParseException&)
{
//
// Ignore all warnings.
//
}
void DOMTreeErrorReporter::error(const SAXParseException& toCatch)
{
fSawErrors = true;
cerr << "Error at file \"" << StrX(toCatch.getSystemId())
<< "\", line " << toCatch.getLineNumber()
<< ", column " << toCatch.getColumnNumber()
<< "\n Message: " << StrX(toCatch.getMessage()) << endl;
}
void DOMTreeErrorReporter::fatalError(const SAXParseException& toCatch)
{
fSawErrors = true;
cerr << "Fatal Error at file \"" << StrX(toCatch.getSystemId())
<< "\", line " << toCatch.getLineNumber()
<< ", column " << toCatch.getColumnNumber()
<< "\n Message: " << StrX(toCatch.getMessage()) << endl;
}
void DOMTreeErrorReporter::resetErrors()
{
// No-op in this case
}
<commit_msg>DOMPrint minor update: reset fSawErrors in DOMTreeErrorReporter::resetErrors<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/sax/SAXParseException.hpp>
#include "DOMTreeErrorReporter.hpp"
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
void DOMTreeErrorReporter::warning(const SAXParseException&)
{
//
// Ignore all warnings.
//
}
void DOMTreeErrorReporter::error(const SAXParseException& toCatch)
{
fSawErrors = true;
cerr << "Error at file \"" << StrX(toCatch.getSystemId())
<< "\", line " << toCatch.getLineNumber()
<< ", column " << toCatch.getColumnNumber()
<< "\n Message: " << StrX(toCatch.getMessage()) << endl;
}
void DOMTreeErrorReporter::fatalError(const SAXParseException& toCatch)
{
fSawErrors = true;
cerr << "Fatal Error at file \"" << StrX(toCatch.getSystemId())
<< "\", line " << toCatch.getLineNumber()
<< ", column " << toCatch.getColumnNumber()
<< "\n Message: " << StrX(toCatch.getMessage()) << endl;
}
void DOMTreeErrorReporter::resetErrors()
{
fSawErrors = false;
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/sax/SAXParseException.hpp>
#include "DOMTreeErrorReporter.hpp"
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
void DOMTreeErrorReporter::warning(const SAXParseException&)
{
//
// Ignore all warnings.
//
}
void DOMTreeErrorReporter::error(const SAXParseException& toCatch)
{
fSawErrors = true;
cerr << "Error at file \"" << StrX(toCatch.getSystemId())
<< "\", line " << toCatch.getLineNumber()
<< ", column " << toCatch.getColumnNumber()
<< "\n Message: " << StrX(toCatch.getMessage()) << endl;
}
void DOMTreeErrorReporter::fatalError(const SAXParseException& toCatch)
{
fSawErrors = true;
cerr << "Fatal Error at file \"" << StrX(toCatch.getSystemId())
<< "\", line " << toCatch.getLineNumber()
<< ", column " << toCatch.getColumnNumber()
<< "\n Message: " << StrX(toCatch.getMessage()) << endl;
}
void DOMTreeErrorReporter::resetErrors()
{
// No-op in this case
}
<commit_msg>DOMPrint minor update: reset fSawErrors in DOMTreeErrorReporter::resetErrors<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/sax/SAXParseException.hpp>
#include "DOMTreeErrorReporter.hpp"
#include <iostream.h>
#include <stdlib.h>
#include <string.h>
void DOMTreeErrorReporter::warning(const SAXParseException&)
{
//
// Ignore all warnings.
//
}
void DOMTreeErrorReporter::error(const SAXParseException& toCatch)
{
fSawErrors = true;
cerr << "Error at file \"" << StrX(toCatch.getSystemId())
<< "\", line " << toCatch.getLineNumber()
<< ", column " << toCatch.getColumnNumber()
<< "\n Message: " << StrX(toCatch.getMessage()) << endl;
}
void DOMTreeErrorReporter::fatalError(const SAXParseException& toCatch)
{
fSawErrors = true;
cerr << "Fatal Error at file \"" << StrX(toCatch.getSystemId())
<< "\", line " << toCatch.getLineNumber()
<< ", column " << toCatch.getColumnNumber()
<< "\n Message: " << StrX(toCatch.getMessage()) << endl;
}
void DOMTreeErrorReporter::resetErrors()
{
fSawErrors = false;
}
<|endoftext|> |
<commit_before>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/multiview/translation_averaging_common.hpp"
#include "openMVG/multiview/translation_averaging_solver.hpp"
#include "openMVG/numeric/eigen_alias_definition.hpp"
#include "openMVG/types.hpp"
#ifdef OPENMVG_USE_OPENMP
#include <omp.h>
#endif
#include <ceres/ceres.h>
#include <ceres/rotation.h>
#include <vector>
namespace openMVG {
// Main Cost functor for translation averaging:
// measure the consistency (residual error) from the relative translations (constant) to the scales and global camera translations
struct RelativeTranslationError
{
RelativeTranslationError
(
double t_ij_x,
double t_ij_y,
double t_ij_z
)
: t_ij_x_(t_ij_x), t_ij_y_(t_ij_y), t_ij_z_(t_ij_z)
{}
template <typename T>
bool operator()
(
const T* const t_i,
const T* const t_j,
const T* const R_ij,
const T* const s_ij,
T* residuals
) const
{
//
// residual = t_j - R_ij t_i - s_ij * t_ij
//
T rotated_t_i[3];
// Rotate the point according the relative local rotation
ceres::AngleAxisRotatePoint(R_ij, t_i, rotated_t_i);
residuals[0] = T(t_j[0] - rotated_t_i[0] - *s_ij * t_ij_x_);
residuals[1] = T(t_j[1] - rotated_t_i[1] - *s_ij * t_ij_y_);
residuals[2] = T(t_j[2] - rotated_t_i[2] - *s_ij * t_ij_z_);
return true;
}
double t_ij_x_, t_ij_y_, t_ij_z_;
};
// Cost penalizing scales smaller than 1.
struct SmallScaleError
{
explicit SmallScaleError
(
double weight = 1.0
)
: weight_(weight)
{}
template <typename T>
bool operator()
(
const T* const s_ij, T* residual
) const
{
residual[0] = (*s_ij > T(1.0)) ? T(0.0) : (T(weight_) * (T(1.0) - *s_ij));
return true;
}
double weight_;
};
bool solve_translations_problem_softl1
(
const std::vector<openMVG::RelativeInfo_Vec > & vec_relative_group_estimates,
std::vector<Eigen::Vector3d> & translations,
const double d_l1_loss_threshold
)
{
//-- Count:
//- #poses are used by the relative position estimates
//- #relative estimates we will use
std::set<unsigned int> count_set;
unsigned int relative_info_count = 0;
for (const openMVG::RelativeInfo_Vec & iter : vec_relative_group_estimates)
{
for (const relativeInfo & it_relative_motion : iter)
{
++relative_info_count;
count_set.insert(it_relative_motion.first.first);
count_set.insert(it_relative_motion.first.second);
}
}
const IndexT nb_poses = count_set.size();
//--
// Build the parameters arrays:
//--
// - camera translations
// - relative translation scales (one per group)
// - relative rotations
std::vector<double> vec_translations(relative_info_count*3, 1.0);
const unsigned nb_scales = vec_relative_group_estimates.size();
std::vector<double> vec_scales(nb_scales, 1.0);
// Setup the relative rotations array (angle axis parametrization)
std::vector<double> vec_relative_rotations(relative_info_count*3, 0.0);
unsigned int cpt = 0;
for (const openMVG::RelativeInfo_Vec & iter : vec_relative_group_estimates)
{
for (const relativeInfo & info : iter)
{
ceres::RotationMatrixToAngleAxis(
(const double*)info.second.first.data(),
&vec_relative_rotations[cpt]);
cpt += 3;
}
}
ceres::LossFunction * loss =
(d_l1_loss_threshold < 0) ? nullptr : new ceres::SoftLOneLoss(d_l1_loss_threshold);
// Add constraints to the minimization problem
ceres::Problem problem;
//
// A. Add cost functors:
cpt = 0;
IndexT scale_idx = 0;
for (const openMVG::RelativeInfo_Vec & iter : vec_relative_group_estimates)
{
for (const relativeInfo & info : iter)
{
const Pair & ids = info.first;
const IndexT I = ids.first;
const IndexT J = ids.second;
const Vec3 t_ij = info.second.second;
// Each Residual block takes 2 camera translations & the relative rotation & a scale
// and outputs a 3 dimensional residual.
ceres::CostFunction* cost_function =
new ceres::AutoDiffCostFunction<RelativeTranslationError, 3, 3, 3, 3,1>(
new RelativeTranslationError(t_ij(0), t_ij(1), t_ij(2)));
problem.AddResidualBlock(
cost_function,
loss,
&vec_translations[I*3],
&vec_translations[J*3],
&vec_relative_rotations[cpt],
&vec_scales[scale_idx]);
// the relative rotation is set as constant
problem.SetParameterBlockConstant(&vec_relative_rotations[cpt]);
cpt+=3;
}
++scale_idx; // One scale per relative_motion group
}
// B. Add constraint over the scale factors:
// Prefer scale > 1, since a trivial solution is translations = {0,...,0}).
for (unsigned i = 0; i < nb_scales; ++i)
{
ceres::CostFunction* cost_function =
new ceres::AutoDiffCostFunction<SmallScaleError, 1, 1>(
new SmallScaleError(1.0));
problem.AddResidualBlock(cost_function, nullptr, &vec_scales[i]);
}
// Set one center as known (to fix the gauge freedom)
vec_translations[0] = vec_translations[1] = vec_translations[2] = 0.0;
problem.SetParameterBlockConstant(&vec_translations[0]);
// Solve
ceres::Solver::Options options;
options.minimizer_progress_to_stdout = false;
if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::SUITE_SPARSE))
{
options.sparse_linear_algebra_library_type = ceres::SUITE_SPARSE;
options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
}
else if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::CX_SPARSE))
{
options.sparse_linear_algebra_library_type = ceres::CX_SPARSE;
options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
}
else if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::EIGEN_SPARSE))
{
options.sparse_linear_algebra_library_type = ceres::EIGEN_SPARSE;
options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
}
else
{
options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY;
}
options.max_num_iterations = std::max(50, (int)(nb_scales * 2));
options.minimizer_progress_to_stdout = false;
options.logging_type = ceres::SILENT;
#ifdef OPENMVG_USE_OPENMP
options.num_threads = omp_get_max_threads();
#if CERES_VERSION_MAJOR < 2
options.num_linear_solver_threads = omp_get_max_threads();
#endif
#endif // OPENMVG_USE_OPENMP
ceres::Solver::Summary summary;
ceres::Solve(options, &problem, &summary);
if (!summary.IsSolutionUsable())
{
std::cout << summary.FullReport() << std::endl;
return false;
}
// Fill the global translations array
translations.resize(nb_poses);
cpt = 0;
for (unsigned int i = 0; i < nb_poses; ++i, cpt+=3)
{
translations[i] << vec_translations[cpt], vec_translations[cpt+1], vec_translations[cpt+2];
}
return true;
}
} // namespace openMVG
<commit_msg>[multiview] Fix size of the translation vector (#1926)<commit_after>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2015 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/multiview/translation_averaging_common.hpp"
#include "openMVG/multiview/translation_averaging_solver.hpp"
#include "openMVG/numeric/eigen_alias_definition.hpp"
#include "openMVG/types.hpp"
#ifdef OPENMVG_USE_OPENMP
#include <omp.h>
#endif
#include <ceres/ceres.h>
#include <ceres/rotation.h>
#include <vector>
namespace openMVG {
// Main Cost functor for translation averaging:
// measure the consistency (residual error) from the relative translations (constant) to the scales and global camera translations
struct RelativeTranslationError
{
RelativeTranslationError
(
double t_ij_x,
double t_ij_y,
double t_ij_z
)
: t_ij_x_(t_ij_x), t_ij_y_(t_ij_y), t_ij_z_(t_ij_z)
{}
template <typename T>
bool operator()
(
const T* const t_i,
const T* const t_j,
const T* const R_ij,
const T* const s_ij,
T* residuals
) const
{
//
// residual = t_j - R_ij t_i - s_ij * t_ij
//
T rotated_t_i[3];
// Rotate the point according the relative local rotation
ceres::AngleAxisRotatePoint(R_ij, t_i, rotated_t_i);
residuals[0] = T(t_j[0] - rotated_t_i[0] - *s_ij * t_ij_x_);
residuals[1] = T(t_j[1] - rotated_t_i[1] - *s_ij * t_ij_y_);
residuals[2] = T(t_j[2] - rotated_t_i[2] - *s_ij * t_ij_z_);
return true;
}
double t_ij_x_, t_ij_y_, t_ij_z_;
};
// Cost penalizing scales smaller than 1.
struct SmallScaleError
{
explicit SmallScaleError
(
double weight = 1.0
)
: weight_(weight)
{}
template <typename T>
bool operator()
(
const T* const s_ij, T* residual
) const
{
residual[0] = (*s_ij > T(1.0)) ? T(0.0) : (T(weight_) * (T(1.0) - *s_ij));
return true;
}
double weight_;
};
bool solve_translations_problem_softl1
(
const std::vector<openMVG::RelativeInfo_Vec > & vec_relative_group_estimates,
std::vector<Eigen::Vector3d> & translations,
const double d_l1_loss_threshold
)
{
//-- Count:
//- #poses are used by the relative position estimates
//- #relative estimates we will use
std::set<unsigned int> count_set;
unsigned int relative_info_count = 0;
for (const openMVG::RelativeInfo_Vec & iter : vec_relative_group_estimates)
{
for (const relativeInfo & it_relative_motion : iter)
{
++relative_info_count;
count_set.insert(it_relative_motion.first.first);
count_set.insert(it_relative_motion.first.second);
}
}
const IndexT nb_poses = count_set.size();
//--
// Build the parameters arrays:
//--
// - camera translations
// - relative translation scales (one per group)
// - relative rotations
std::vector<double> vec_translations(nb_poses*3, 1.0);
const unsigned nb_scales = vec_relative_group_estimates.size();
std::vector<double> vec_scales(nb_scales, 1.0);
// Setup the relative rotations array (angle axis parametrization)
std::vector<double> vec_relative_rotations(relative_info_count*3, 0.0);
unsigned int cpt = 0;
for (const openMVG::RelativeInfo_Vec & iter : vec_relative_group_estimates)
{
for (const relativeInfo & info : iter)
{
ceres::RotationMatrixToAngleAxis(
(const double*)info.second.first.data(),
&vec_relative_rotations[cpt]);
cpt += 3;
}
}
ceres::LossFunction * loss =
(d_l1_loss_threshold < 0) ? nullptr : new ceres::SoftLOneLoss(d_l1_loss_threshold);
// Add constraints to the minimization problem
ceres::Problem problem;
//
// A. Add cost functors:
cpt = 0;
IndexT scale_idx = 0;
for (const openMVG::RelativeInfo_Vec & iter : vec_relative_group_estimates)
{
for (const relativeInfo & info : iter)
{
const Pair & ids = info.first;
const IndexT I = ids.first;
const IndexT J = ids.second;
const Vec3 t_ij = info.second.second;
// Each Residual block takes 2 camera translations & the relative rotation & a scale
// and outputs a 3 dimensional residual.
ceres::CostFunction* cost_function =
new ceres::AutoDiffCostFunction<RelativeTranslationError, 3, 3, 3, 3,1>(
new RelativeTranslationError(t_ij(0), t_ij(1), t_ij(2)));
problem.AddResidualBlock(
cost_function,
loss,
&vec_translations[I*3],
&vec_translations[J*3],
&vec_relative_rotations[cpt],
&vec_scales[scale_idx]);
// the relative rotation is set as constant
problem.SetParameterBlockConstant(&vec_relative_rotations[cpt]);
cpt+=3;
}
++scale_idx; // One scale per relative_motion group
}
// B. Add constraint over the scale factors:
// Prefer scale > 1, since a trivial solution is translations = {0,...,0}).
for (unsigned i = 0; i < nb_scales; ++i)
{
ceres::CostFunction* cost_function =
new ceres::AutoDiffCostFunction<SmallScaleError, 1, 1>(
new SmallScaleError(1.0));
problem.AddResidualBlock(cost_function, nullptr, &vec_scales[i]);
}
// Set one center as known (to fix the gauge freedom)
vec_translations[0] = vec_translations[1] = vec_translations[2] = 0.0;
problem.SetParameterBlockConstant(&vec_translations[0]);
// Solve
ceres::Solver::Options options;
options.minimizer_progress_to_stdout = false;
if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::SUITE_SPARSE))
{
options.sparse_linear_algebra_library_type = ceres::SUITE_SPARSE;
options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
}
else if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::CX_SPARSE))
{
options.sparse_linear_algebra_library_type = ceres::CX_SPARSE;
options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
}
else if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::EIGEN_SPARSE))
{
options.sparse_linear_algebra_library_type = ceres::EIGEN_SPARSE;
options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
}
else
{
options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY;
}
options.max_num_iterations = std::max(50, (int)(nb_scales * 2));
options.minimizer_progress_to_stdout = false;
options.logging_type = ceres::SILENT;
#ifdef OPENMVG_USE_OPENMP
options.num_threads = omp_get_max_threads();
#if CERES_VERSION_MAJOR < 2
options.num_linear_solver_threads = omp_get_max_threads();
#endif
#endif // OPENMVG_USE_OPENMP
ceres::Solver::Summary summary;
ceres::Solve(options, &problem, &summary);
if (!summary.IsSolutionUsable())
{
std::cout << summary.FullReport() << std::endl;
return false;
}
// Fill the global translations array
translations.resize(nb_poses);
cpt = 0;
for (unsigned int i = 0; i < nb_poses; ++i, cpt+=3)
{
translations[i] = Eigen::Map<Eigen::Vector3d>(&vec_translations[cpt]);
}
return true;
}
} // namespace openMVG
<|endoftext|> |
<commit_before>#include "BatteryPopulator.h"
BatteryPopulator::BatteryPopulator(I_PacketDecoder& packetDecoder,
I_BatteryData& batteryData)
: packetDecoder_(packetDecoder_)
, batteryData_(batteryData)
{
connect(&packetDecoder_, SIGNAL(packetDecoded(const BatteryDataMessage)),
this, SLOT(populateData(const FaultsMessage)));
}
void BatteryPopulator::populateData(const BatteryDataMessage message)
{
batteryData_.setBatteryVoltage(message.batteryVoltage());
batteryData_.setBatteryCurrent(message.batteryCurrent());
// batteryData_.set***SOMETHINGHERE***(message.stateOfCharge());
// batteryData_.set***SOMETHINGHERE***(message.balanceStateOfCharge());
// batteryData_.set***SOMETHINGHERE***(message.secondaryBatteryUnderVoltage());
}
<commit_msg>fixed segfault error in batterypopulator<commit_after>#include "BatteryPopulator.h"
BatteryPopulator::BatteryPopulator(I_PacketDecoder& packetDecoder,
I_BatteryData& batteryData)
: packetDecoder_(packetDecoder)
, batteryData_(batteryData)
{
connect(&packetDecoder_, SIGNAL(packetDecoded(const BatteryDataMessage)),
this, SLOT(populateData(const BatteryDataMessage)));
}
void BatteryPopulator::populateData(const BatteryDataMessage message)
{
batteryData_.setBatteryVoltage(message.batteryVoltage());
batteryData_.setBatteryCurrent(message.batteryCurrent());
// batteryData_.set***SOMETHINGHERE***(message.stateOfCharge());
// batteryData_.set***SOMETHINGHERE***(message.balanceStateOfCharge());
// batteryData_.set***SOMETHINGHERE***(message.secondaryBatteryUnderVoltage());
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Real Logic Ltd.
*
* 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 <iostream>
#include "gtest/gtest.h"
#include "code_generation_test/MessageHeader.hpp"
#include "code_generation_test/Car.hpp"
using namespace std;
using namespace code_generation_test;
#define SERIAL_NUMBER 1234u
#define MODEL_YEAR 2013
#define AVAILABLE (BooleanType::T)
#define CODE (Model::A)
#define CRUISE_CONTROL (true)
#define SPORTS_PACK (true)
#define SUNROOF (false)
static char VEHICLE_CODE[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
static char MANUFACTURER_CODE[] = { '1', '2', '3' };
static const char *MAKE = "Honda";
static const char *MODEL = "Civic VTi";
static const char *ACTIVATION_CODE = "deadbeef";
static const int encodedHdrSz = 8;
static const int encodedCarSz = 179;
class BoundsCheckTest : public testing::Test
{
public:
virtual int encodeHdr(char *buffer, int offset, int bufferLength)
{
m_hdr.wrap(buffer, offset, 0, bufferLength)
.blockLength(Car::sbeBlockLength())
.templateId(Car::sbeTemplateId())
.schemaId(Car::sbeSchemaId())
.version(Car::sbeSchemaVersion());
return m_hdr.size();
}
virtual int decodeHdr(char *buffer, int offset, int bufferLength)
{
m_hdrDecoder.wrap(buffer, offset, 0, bufferLength);
EXPECT_EQ(m_hdrDecoder.blockLength(), Car::sbeBlockLength());
EXPECT_EQ(m_hdrDecoder.templateId(), Car::sbeTemplateId());
EXPECT_EQ(m_hdrDecoder.schemaId(), Car::sbeSchemaId());
EXPECT_EQ(m_hdrDecoder.version(), Car::sbeSchemaVersion());
return m_hdrDecoder.size();
}
virtual int encodeCarRoot(char *buffer, int offset, int bufferLength)
{
m_car.wrapForEncode(buffer, offset, bufferLength)
.serialNumber(SERIAL_NUMBER)
.modelYear(MODEL_YEAR)
.available(AVAILABLE)
.code(CODE)
.putVehicleCode(VEHICLE_CODE);
for (int i = 0; i < Car::someNumbersLength(); i++)
{
m_car.someNumbers(i, i);
}
m_car.extras().clear()
.cruiseControl(CRUISE_CONTROL)
.sportsPack(SPORTS_PACK)
.sunRoof(SUNROOF);
m_car.engine()
.capacity(2000)
.numCylinders((short)4)
.putManufacturerCode(MANUFACTURER_CODE);
return m_car.size();
}
virtual int encodeCarFuelFigures()
{
Car::FuelFigures& fuelFigures = m_car.fuelFiguresCount(3);
fuelFigures
.next().speed(30).mpg(35.9f);
fuelFigures.putUsageDescription("Urban Cycle", 11);
fuelFigures
.next().speed(55).mpg(49.0f);
fuelFigures.putUsageDescription("Combined Cycle", 14);
fuelFigures
.next().speed(75).mpg(40.0f);
fuelFigures.putUsageDescription("Highway Cycle", 13);
return m_car.size();
}
virtual int encodeCarPerformanceFigures()
{
Car::PerformanceFigures &perfFigs = m_car.performanceFiguresCount(2);
perfFigs.next()
.octaneRating((short)95)
.accelerationCount(3)
.next().mph(30).seconds(4.0f)
.next().mph(60).seconds(7.5f)
.next().mph(100).seconds(12.2f);
perfFigs.next()
.octaneRating((short)99)
.accelerationCount(3)
.next().mph(30).seconds(3.8f)
.next().mph(60).seconds(7.1f)
.next().mph(100).seconds(11.8f);
return m_car.size();
}
virtual int encodeCarMakeModelAndActivationCode()
{
m_car.putMake(MAKE, static_cast<int>(strlen(MAKE)));
m_car.putModel(MODEL, static_cast<int>(strlen(MODEL)));
m_car.putActivationCode(ACTIVATION_CODE, static_cast<int>(strlen(ACTIVATION_CODE)));
return m_car.size();
}
virtual int decodeCarRoot(char *buffer, const int offset, const int bufferLength)
{
m_carDecoder.wrapForDecode(buffer, offset, Car::sbeBlockLength(), Car::sbeSchemaVersion(), bufferLength);
EXPECT_EQ(m_carDecoder.serialNumber(), SERIAL_NUMBER);
EXPECT_EQ(m_carDecoder.modelYear(), MODEL_YEAR);
EXPECT_EQ(m_carDecoder.available(), AVAILABLE);
EXPECT_EQ(m_carDecoder.code(), CODE);
EXPECT_EQ(m_carDecoder.someNumbersLength(), 5);
for (int i = 0; i < 5; i++)
{
EXPECT_EQ(m_carDecoder.someNumbers(i), i);
}
EXPECT_EQ(m_carDecoder.vehicleCodeLength(), 6);
EXPECT_EQ(std::string(m_carDecoder.vehicleCode(), 6), std::string(VEHICLE_CODE, 6));
EXPECT_EQ(m_carDecoder.extras().cruiseControl(), true);
EXPECT_EQ(m_carDecoder.extras().sportsPack(), true);
EXPECT_EQ(m_carDecoder.extras().sunRoof(), false);
Engine &engine = m_carDecoder.engine();
EXPECT_EQ(engine.capacity(), 2000);
EXPECT_EQ(engine.numCylinders(), 4);
EXPECT_EQ(engine.maxRpm(), 9000);
EXPECT_EQ(engine.manufacturerCodeLength(), 3);
EXPECT_EQ(std::string(engine.manufacturerCode(), 3), std::string(MANUFACTURER_CODE, 3));
EXPECT_EQ(engine.fuelLength(), 6);
EXPECT_EQ(std::string(engine.fuel(), 6), std::string("Petrol"));
return m_carDecoder.size();
}
virtual int decodeCarFuelFigures()
{
char tmp[256];
Car::FuelFigures &fuelFigures = m_carDecoder.fuelFigures();
EXPECT_EQ(fuelFigures.count(), 3);
EXPECT_TRUE(fuelFigures.hasNext());
fuelFigures.next();
EXPECT_EQ(fuelFigures.speed(), 30);
EXPECT_EQ(fuelFigures.mpg(), 35.9f);
EXPECT_EQ(fuelFigures.getUsageDescription(tmp, sizeof(tmp)), 11);
EXPECT_EQ(std::string(tmp, 11), "Urban Cycle");
EXPECT_TRUE(fuelFigures.hasNext());
fuelFigures.next();
EXPECT_EQ(fuelFigures.speed(), 55);
EXPECT_EQ(fuelFigures.mpg(), 49.0f);
EXPECT_EQ(fuelFigures.getUsageDescription(tmp, sizeof(tmp)), 14);
EXPECT_EQ(std::string(tmp, 14), "Combined Cycle");
EXPECT_TRUE(fuelFigures.hasNext());
fuelFigures.next();
EXPECT_EQ(fuelFigures.speed(), 75);
EXPECT_EQ(fuelFigures.mpg(), 40.0f);
EXPECT_EQ(fuelFigures.getUsageDescription(tmp, sizeof(tmp)), 13);
EXPECT_EQ(std::string(tmp, 13), "Highway Cycle");
return m_carDecoder.size();
}
virtual int decodeCarPerformanceFigures()
{
Car::PerformanceFigures &performanceFigures = m_carDecoder.performanceFigures();
EXPECT_EQ(performanceFigures.count(), 2);
EXPECT_TRUE(performanceFigures.hasNext());
performanceFigures.next();
EXPECT_EQ(performanceFigures.octaneRating(), 95);
Car::PerformanceFigures::Acceleration &acceleration = performanceFigures.acceleration();
EXPECT_EQ(acceleration.count(), 3);
EXPECT_TRUE(acceleration.hasNext());
acceleration.next();
EXPECT_EQ(acceleration.mph(), 30);
EXPECT_EQ(acceleration.seconds(), 4.0f);
EXPECT_TRUE(acceleration.hasNext());
acceleration.next();
EXPECT_EQ(acceleration.mph(), 60);
EXPECT_EQ(acceleration.seconds(), 7.5f);
EXPECT_TRUE(acceleration.hasNext());
acceleration.next();
EXPECT_EQ(acceleration.mph(), 100);
EXPECT_EQ(acceleration.seconds(), 12.2f);
EXPECT_TRUE(performanceFigures.hasNext());
performanceFigures.next();
EXPECT_EQ(performanceFigures.octaneRating(), 99);
acceleration = performanceFigures.acceleration();
EXPECT_EQ(acceleration.count(), 3);
EXPECT_TRUE(acceleration.hasNext());
acceleration.next();
EXPECT_EQ(acceleration.mph(), 30);
EXPECT_EQ(acceleration.seconds(), 3.8f);
EXPECT_TRUE(acceleration.hasNext());
acceleration.next();
EXPECT_EQ(acceleration.mph(), 60);
EXPECT_EQ(acceleration.seconds(), 7.1f);
EXPECT_TRUE(acceleration.hasNext());
acceleration.next();
EXPECT_EQ(acceleration.mph(), 100);
EXPECT_EQ(acceleration.seconds(), 11.8f);
return m_carDecoder.size();
}
virtual int decodeCarMakeModelAndActivationCode()
{
char tmp[256];
EXPECT_EQ(m_carDecoder.getMake(tmp, sizeof(tmp)), 5);
EXPECT_EQ(std::string(tmp, 5), "Honda");
EXPECT_EQ(m_carDecoder.getModel(tmp, sizeof(tmp)), 9);
EXPECT_EQ(std::string(tmp, 9), "Civic VTi");
EXPECT_EQ(m_carDecoder.getActivationCode(tmp, sizeof(tmp)), 8);
EXPECT_EQ(std::string(tmp, 8), "deadbeef");
EXPECT_EQ(m_carDecoder.size(), encodedCarSz);
return m_carDecoder.size();
}
MessageHeader m_hdr;
MessageHeader m_hdrDecoder;
Car m_car;
Car m_carDecoder;
};
class HeaderBoundsCheckTest : public BoundsCheckTest, public ::testing::WithParamInterface<int>
{
};
TEST_P(HeaderBoundsCheckTest, shouldExceptionWhenBufferTooShortForEncodeOfHeader)
{
const int length = GetParam();
std::unique_ptr<char[]> buffer(new char[length]);
EXPECT_THROW(
{
encodeHdr(buffer.get(), 0, length);
}, std::runtime_error);
}
TEST_P(HeaderBoundsCheckTest, shouldExceptionWhenBufferTooShortForDecodeOfHeader)
{
const int length = GetParam();
char encodeBuffer[MessageHeader::size()];
std::unique_ptr<char[]> buffer(new char[length]);
encodeHdr(encodeBuffer, 0, sizeof(encodeBuffer));
EXPECT_THROW(
{
std::memcpy(buffer.get(), encodeBuffer, length);
decodeHdr(buffer.get(), 0, length);
}, std::runtime_error);
}
INSTANTIATE_TEST_CASE_P(
HeaderLengthTest,
HeaderBoundsCheckTest,
::testing::Range(0, encodedHdrSz, 1));
class MessageBoundsCheckTest : public BoundsCheckTest, public ::testing::WithParamInterface<int>
{
};
TEST_P(MessageBoundsCheckTest, shouldExceptionWhenBufferTooShortForEncodeOfMessage)
{
const int length = GetParam();
std::unique_ptr<char[]> buffer(new char[length]);
EXPECT_THROW(
{
encodeCarRoot(buffer.get(), 0, length);
encodeCarFuelFigures();
encodeCarPerformanceFigures();
encodeCarMakeModelAndActivationCode();
}, std::runtime_error);
}
TEST_P(MessageBoundsCheckTest, shouldExceptionWhenBufferTooShortForDecodeOfMessage)
{
const int length = GetParam();
char encodeBuffer[179];
std::unique_ptr<char[]> buffer(new char[length]);
encodeCarRoot(encodeBuffer, 0, sizeof(encodeBuffer));
encodeCarFuelFigures();
encodeCarPerformanceFigures();
encodeCarMakeModelAndActivationCode();
EXPECT_THROW(
{
std::memcpy(buffer.get(), encodeBuffer, length);
decodeCarRoot(buffer.get(), 0, length);
decodeCarFuelFigures();
decodeCarPerformanceFigures();
decodeCarMakeModelAndActivationCode();
}, std::runtime_error);
}
INSTANTIATE_TEST_CASE_P(
MessageLengthTest,
MessageBoundsCheckTest,
::testing::Range(0, encodedCarSz, 1));
<commit_msg>[C++]: add missing includes for Linux g++<commit_after>/*
* Copyright 2014 Real Logic Ltd.
*
* 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 <iostream>
#include <memory>
#include <cstring>
#include "gtest/gtest.h"
#include "code_generation_test/MessageHeader.hpp"
#include "code_generation_test/Car.hpp"
using namespace std;
using namespace code_generation_test;
#define SERIAL_NUMBER 1234u
#define MODEL_YEAR 2013
#define AVAILABLE (BooleanType::T)
#define CODE (Model::A)
#define CRUISE_CONTROL (true)
#define SPORTS_PACK (true)
#define SUNROOF (false)
static char VEHICLE_CODE[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
static char MANUFACTURER_CODE[] = { '1', '2', '3' };
static const char *MAKE = "Honda";
static const char *MODEL = "Civic VTi";
static const char *ACTIVATION_CODE = "deadbeef";
static const int encodedHdrSz = 8;
static const int encodedCarSz = 179;
class BoundsCheckTest : public testing::Test
{
public:
virtual int encodeHdr(char *buffer, int offset, int bufferLength)
{
m_hdr.wrap(buffer, offset, 0, bufferLength)
.blockLength(Car::sbeBlockLength())
.templateId(Car::sbeTemplateId())
.schemaId(Car::sbeSchemaId())
.version(Car::sbeSchemaVersion());
return m_hdr.size();
}
virtual int decodeHdr(char *buffer, int offset, int bufferLength)
{
m_hdrDecoder.wrap(buffer, offset, 0, bufferLength);
EXPECT_EQ(m_hdrDecoder.blockLength(), Car::sbeBlockLength());
EXPECT_EQ(m_hdrDecoder.templateId(), Car::sbeTemplateId());
EXPECT_EQ(m_hdrDecoder.schemaId(), Car::sbeSchemaId());
EXPECT_EQ(m_hdrDecoder.version(), Car::sbeSchemaVersion());
return m_hdrDecoder.size();
}
virtual int encodeCarRoot(char *buffer, int offset, int bufferLength)
{
m_car.wrapForEncode(buffer, offset, bufferLength)
.serialNumber(SERIAL_NUMBER)
.modelYear(MODEL_YEAR)
.available(AVAILABLE)
.code(CODE)
.putVehicleCode(VEHICLE_CODE);
for (int i = 0; i < Car::someNumbersLength(); i++)
{
m_car.someNumbers(i, i);
}
m_car.extras().clear()
.cruiseControl(CRUISE_CONTROL)
.sportsPack(SPORTS_PACK)
.sunRoof(SUNROOF);
m_car.engine()
.capacity(2000)
.numCylinders((short)4)
.putManufacturerCode(MANUFACTURER_CODE);
return m_car.size();
}
virtual int encodeCarFuelFigures()
{
Car::FuelFigures& fuelFigures = m_car.fuelFiguresCount(3);
fuelFigures
.next().speed(30).mpg(35.9f);
fuelFigures.putUsageDescription("Urban Cycle", 11);
fuelFigures
.next().speed(55).mpg(49.0f);
fuelFigures.putUsageDescription("Combined Cycle", 14);
fuelFigures
.next().speed(75).mpg(40.0f);
fuelFigures.putUsageDescription("Highway Cycle", 13);
return m_car.size();
}
virtual int encodeCarPerformanceFigures()
{
Car::PerformanceFigures &perfFigs = m_car.performanceFiguresCount(2);
perfFigs.next()
.octaneRating((short)95)
.accelerationCount(3)
.next().mph(30).seconds(4.0f)
.next().mph(60).seconds(7.5f)
.next().mph(100).seconds(12.2f);
perfFigs.next()
.octaneRating((short)99)
.accelerationCount(3)
.next().mph(30).seconds(3.8f)
.next().mph(60).seconds(7.1f)
.next().mph(100).seconds(11.8f);
return m_car.size();
}
virtual int encodeCarMakeModelAndActivationCode()
{
m_car.putMake(MAKE, static_cast<int>(strlen(MAKE)));
m_car.putModel(MODEL, static_cast<int>(strlen(MODEL)));
m_car.putActivationCode(ACTIVATION_CODE, static_cast<int>(strlen(ACTIVATION_CODE)));
return m_car.size();
}
virtual int decodeCarRoot(char *buffer, const int offset, const int bufferLength)
{
m_carDecoder.wrapForDecode(buffer, offset, Car::sbeBlockLength(), Car::sbeSchemaVersion(), bufferLength);
EXPECT_EQ(m_carDecoder.serialNumber(), SERIAL_NUMBER);
EXPECT_EQ(m_carDecoder.modelYear(), MODEL_YEAR);
EXPECT_EQ(m_carDecoder.available(), AVAILABLE);
EXPECT_EQ(m_carDecoder.code(), CODE);
EXPECT_EQ(m_carDecoder.someNumbersLength(), 5);
for (int i = 0; i < 5; i++)
{
EXPECT_EQ(m_carDecoder.someNumbers(i), i);
}
EXPECT_EQ(m_carDecoder.vehicleCodeLength(), 6);
EXPECT_EQ(std::string(m_carDecoder.vehicleCode(), 6), std::string(VEHICLE_CODE, 6));
EXPECT_EQ(m_carDecoder.extras().cruiseControl(), true);
EXPECT_EQ(m_carDecoder.extras().sportsPack(), true);
EXPECT_EQ(m_carDecoder.extras().sunRoof(), false);
Engine &engine = m_carDecoder.engine();
EXPECT_EQ(engine.capacity(), 2000);
EXPECT_EQ(engine.numCylinders(), 4);
EXPECT_EQ(engine.maxRpm(), 9000);
EXPECT_EQ(engine.manufacturerCodeLength(), 3);
EXPECT_EQ(std::string(engine.manufacturerCode(), 3), std::string(MANUFACTURER_CODE, 3));
EXPECT_EQ(engine.fuelLength(), 6);
EXPECT_EQ(std::string(engine.fuel(), 6), std::string("Petrol"));
return m_carDecoder.size();
}
virtual int decodeCarFuelFigures()
{
char tmp[256];
Car::FuelFigures &fuelFigures = m_carDecoder.fuelFigures();
EXPECT_EQ(fuelFigures.count(), 3);
EXPECT_TRUE(fuelFigures.hasNext());
fuelFigures.next();
EXPECT_EQ(fuelFigures.speed(), 30);
EXPECT_EQ(fuelFigures.mpg(), 35.9f);
EXPECT_EQ(fuelFigures.getUsageDescription(tmp, sizeof(tmp)), 11);
EXPECT_EQ(std::string(tmp, 11), "Urban Cycle");
EXPECT_TRUE(fuelFigures.hasNext());
fuelFigures.next();
EXPECT_EQ(fuelFigures.speed(), 55);
EXPECT_EQ(fuelFigures.mpg(), 49.0f);
EXPECT_EQ(fuelFigures.getUsageDescription(tmp, sizeof(tmp)), 14);
EXPECT_EQ(std::string(tmp, 14), "Combined Cycle");
EXPECT_TRUE(fuelFigures.hasNext());
fuelFigures.next();
EXPECT_EQ(fuelFigures.speed(), 75);
EXPECT_EQ(fuelFigures.mpg(), 40.0f);
EXPECT_EQ(fuelFigures.getUsageDescription(tmp, sizeof(tmp)), 13);
EXPECT_EQ(std::string(tmp, 13), "Highway Cycle");
return m_carDecoder.size();
}
virtual int decodeCarPerformanceFigures()
{
Car::PerformanceFigures &performanceFigures = m_carDecoder.performanceFigures();
EXPECT_EQ(performanceFigures.count(), 2);
EXPECT_TRUE(performanceFigures.hasNext());
performanceFigures.next();
EXPECT_EQ(performanceFigures.octaneRating(), 95);
Car::PerformanceFigures::Acceleration &acceleration = performanceFigures.acceleration();
EXPECT_EQ(acceleration.count(), 3);
EXPECT_TRUE(acceleration.hasNext());
acceleration.next();
EXPECT_EQ(acceleration.mph(), 30);
EXPECT_EQ(acceleration.seconds(), 4.0f);
EXPECT_TRUE(acceleration.hasNext());
acceleration.next();
EXPECT_EQ(acceleration.mph(), 60);
EXPECT_EQ(acceleration.seconds(), 7.5f);
EXPECT_TRUE(acceleration.hasNext());
acceleration.next();
EXPECT_EQ(acceleration.mph(), 100);
EXPECT_EQ(acceleration.seconds(), 12.2f);
EXPECT_TRUE(performanceFigures.hasNext());
performanceFigures.next();
EXPECT_EQ(performanceFigures.octaneRating(), 99);
acceleration = performanceFigures.acceleration();
EXPECT_EQ(acceleration.count(), 3);
EXPECT_TRUE(acceleration.hasNext());
acceleration.next();
EXPECT_EQ(acceleration.mph(), 30);
EXPECT_EQ(acceleration.seconds(), 3.8f);
EXPECT_TRUE(acceleration.hasNext());
acceleration.next();
EXPECT_EQ(acceleration.mph(), 60);
EXPECT_EQ(acceleration.seconds(), 7.1f);
EXPECT_TRUE(acceleration.hasNext());
acceleration.next();
EXPECT_EQ(acceleration.mph(), 100);
EXPECT_EQ(acceleration.seconds(), 11.8f);
return m_carDecoder.size();
}
virtual int decodeCarMakeModelAndActivationCode()
{
char tmp[256];
EXPECT_EQ(m_carDecoder.getMake(tmp, sizeof(tmp)), 5);
EXPECT_EQ(std::string(tmp, 5), "Honda");
EXPECT_EQ(m_carDecoder.getModel(tmp, sizeof(tmp)), 9);
EXPECT_EQ(std::string(tmp, 9), "Civic VTi");
EXPECT_EQ(m_carDecoder.getActivationCode(tmp, sizeof(tmp)), 8);
EXPECT_EQ(std::string(tmp, 8), "deadbeef");
EXPECT_EQ(m_carDecoder.size(), encodedCarSz);
return m_carDecoder.size();
}
MessageHeader m_hdr;
MessageHeader m_hdrDecoder;
Car m_car;
Car m_carDecoder;
};
class HeaderBoundsCheckTest : public BoundsCheckTest, public ::testing::WithParamInterface<int>
{
};
TEST_P(HeaderBoundsCheckTest, shouldExceptionWhenBufferTooShortForEncodeOfHeader)
{
const int length = GetParam();
std::unique_ptr<char[]> buffer(new char[length]);
EXPECT_THROW(
{
encodeHdr(buffer.get(), 0, length);
}, std::runtime_error);
}
TEST_P(HeaderBoundsCheckTest, shouldExceptionWhenBufferTooShortForDecodeOfHeader)
{
const int length = GetParam();
char encodeBuffer[MessageHeader::size()];
std::unique_ptr<char[]> buffer(new char[length]);
encodeHdr(encodeBuffer, 0, sizeof(encodeBuffer));
EXPECT_THROW(
{
std::memcpy(buffer.get(), encodeBuffer, length);
decodeHdr(buffer.get(), 0, length);
}, std::runtime_error);
}
INSTANTIATE_TEST_CASE_P(
HeaderLengthTest,
HeaderBoundsCheckTest,
::testing::Range(0, encodedHdrSz, 1));
class MessageBoundsCheckTest : public BoundsCheckTest, public ::testing::WithParamInterface<int>
{
};
TEST_P(MessageBoundsCheckTest, shouldExceptionWhenBufferTooShortForEncodeOfMessage)
{
const int length = GetParam();
std::unique_ptr<char[]> buffer(new char[length]);
EXPECT_THROW(
{
encodeCarRoot(buffer.get(), 0, length);
encodeCarFuelFigures();
encodeCarPerformanceFigures();
encodeCarMakeModelAndActivationCode();
}, std::runtime_error);
}
TEST_P(MessageBoundsCheckTest, shouldExceptionWhenBufferTooShortForDecodeOfMessage)
{
const int length = GetParam();
char encodeBuffer[179];
std::unique_ptr<char[]> buffer(new char[length]);
encodeCarRoot(encodeBuffer, 0, sizeof(encodeBuffer));
encodeCarFuelFigures();
encodeCarPerformanceFigures();
encodeCarMakeModelAndActivationCode();
EXPECT_THROW(
{
std::memcpy(buffer.get(), encodeBuffer, length);
decodeCarRoot(buffer.get(), 0, length);
decodeCarFuelFigures();
decodeCarPerformanceFigures();
decodeCarMakeModelAndActivationCode();
}, std::runtime_error);
}
INSTANTIATE_TEST_CASE_P(
MessageLengthTest,
MessageBoundsCheckTest,
::testing::Range(0, encodedCarSz, 1));
<|endoftext|> |
<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "dense_lambda_peek_optimizer.h"
#include "dense_tensor_view.h"
#include "dense_replace_type_function.h"
#include "dense_cell_range_function.h"
#include "dense_lambda_peek_function.h"
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/node_tools.h>
#include <vespa/eval/eval/basic_nodes.h>
#include <vespa/eval/eval/operator_nodes.h>
#include <vespa/eval/eval/call_nodes.h>
#include <vespa/eval/eval/tensor_nodes.h>
#include <vespa/eval/eval/llvm/compile_cache.h>
#include <optional>
using namespace vespalib::eval;
using namespace vespalib::eval::nodes;
namespace vespalib::tensor {
namespace {
// 'simple peek': deterministic peek into a single parameter with
// compilable dimension index expressions.
const TensorPeek *find_simple_peek(const tensor_function::Lambda &lambda) {
const Function &function = lambda.lambda();
const size_t num_dims = lambda.result_type().dimensions().size();
auto peek = as<TensorPeek>(function.root());
if (peek && (function.num_params() == (num_dims + 1))) {
auto param = as<Symbol>(peek->get_child(0));
if (param && (param->id() == num_dims)) {
for (size_t i = 1; i < peek->num_children(); ++i) {
const Node &dim_expr = peek->get_child(i);
if (NodeTools::min_num_params(dim_expr) > num_dims) {
return nullptr;
}
if (CompiledFunction::detect_issues(dim_expr)) {
return nullptr;
}
}
return peek;
}
}
return nullptr;
}
Node_UP make_dim_expr(const TensorPeek::Dim &src_dim) {
if (src_dim.second.is_expr()) {
return NodeTools::copy(*src_dim.second.expr);
} else {
return std::make_unique<Number>(as_number(src_dim.second.label));
}
}
template <typename OP>
Node_UP make_op(Node_UP a, Node_UP b) {
auto res = std::make_unique<OP>();
res->bind(std::move(a), std::move(b));
return res;
}
Node_UP make_floor(Node_UP a) {
auto res = std::make_unique<Floor>();
res->bind_next(std::move(a));
return res;
}
struct PeekAnalyzer {
std::vector<size_t> dst_dim_sizes;
std::vector<size_t> src_dim_sizes;
std::vector<CompiledFunction::UP> src_dim_funs;
std::shared_ptr<Function const> src_idx_fun;
struct CellRange {
size_t offset;
size_t length;
bool is_full(size_t num_cells) const {
return ((offset == 0) && (length == num_cells));
}
};
struct Result {
bool valid;
std::optional<CellRange> cell_range;
static Result simple(CellRange range) { return Result{true, range}; }
static Result complex() { return Result{true, std::nullopt}; }
static Result invalid() { return Result{false, std::nullopt}; }
};
PeekAnalyzer(const ValueType &dst_type, const ValueType &src_type,
const TensorPeek::DimList &dim_list)
{
for (const auto dim: dst_type.dimensions()) {
dst_dim_sizes.push_back(dim.size);
}
for (const auto dim: src_type.dimensions()) {
src_dim_sizes.push_back(dim.size);
}
Node_UP idx_expr;
size_t num_params = dst_dim_sizes.size();
for (size_t i = 0; i < dim_list.size(); ++i) {
auto dim_expr = make_dim_expr(dim_list[i]);
src_dim_funs.push_back(std::make_unique<CompiledFunction>(*dim_expr, num_params, PassParams::ARRAY));
if (i == 0) {
idx_expr = std::move(dim_expr);
} else {
idx_expr = make_floor(std::move(idx_expr));
idx_expr = make_op<Mul>(std::move(idx_expr), std::make_unique<Number>(src_dim_sizes[i]));
idx_expr = make_op<Add>(std::move(idx_expr), std::move(dim_expr));
}
}
src_idx_fun = Function::create(std::move(idx_expr), dst_type.dimension_names());
}
bool step_params(std::vector<double> ¶ms) {
for (size_t idx = params.size(); idx-- > 0; ) {
if (size_t(params[idx] += 1.0) < dst_dim_sizes[idx]) {
return true;
} else {
params[idx] = 0.0;
}
}
return false;
}
size_t calculate_index(const std::vector<size_t> &src_address) {
size_t result = 0;
for (size_t i = 0; i < src_address.size(); ++i) {
result *= src_dim_sizes[i];
result += src_address[i];
}
return result;
}
Result analyze_indexes() {
CellRange range{0,0};
bool is_complex = false;
std::vector<double> params(dst_dim_sizes.size(), 0.0);
std::vector<size_t> src_address(src_dim_sizes.size(), 0);
do {
for (size_t i = 0; i < src_dim_funs.size(); ++i) {
auto dim_fun = src_dim_funs[i]->get_function();
size_t dim_idx = dim_fun(¶ms[0]);
if (dim_idx >= src_dim_sizes[i]) {
return Result::invalid();
}
src_address[i] = dim_idx;
}
size_t idx = calculate_index(src_address);
if (range.length == 0) {
range.offset = idx;
}
if (idx == (range.offset + range.length)) {
++range.length;
} else {
is_complex = true;
}
} while(step_params(params));
if (is_complex) {
return Result::complex();
}
return Result::simple(range);
}
};
} // namespace vespalib::tensor::<unnamed>
const TensorFunction &
DenseLambdaPeekOptimizer::optimize(const TensorFunction &expr, Stash &stash)
{
if (auto lambda = as<tensor_function::Lambda>(expr)) {
if (auto peek = find_simple_peek(*lambda)) {
const ValueType &dst_type = lambda->result_type();
const ValueType &src_type = lambda->types().get_type(peek->param());
if (src_type.is_dense()) {
assert(lambda->bindings().size() == 1);
assert(src_type.dimensions().size() == peek->dim_list().size());
size_t param_idx = lambda->bindings()[0];
PeekAnalyzer analyzer(dst_type, src_type, peek->dim_list());
auto result = analyzer.analyze_indexes();
if (result.valid) {
const auto &get_param = tensor_function::inject(src_type, param_idx, stash);
if (result.cell_range && (dst_type.cell_type() == src_type.cell_type())) {
auto cell_range = result.cell_range.value();
if (cell_range.is_full(src_type.dense_subspace_size())) {
return DenseReplaceTypeFunction::create_compact(dst_type, get_param, stash);
} else {
return stash.create<DenseCellRangeFunction>(dst_type, get_param,
cell_range.offset, cell_range.length);
}
} else {
return stash.create<DenseLambdaPeekFunction>(dst_type, get_param,
std::move(analyzer.src_idx_fun));
}
}
}
}
}
return expr;
}
} // namespace vespalib::tensor
<commit_msg>Avoid making copies of container elements.<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "dense_lambda_peek_optimizer.h"
#include "dense_tensor_view.h"
#include "dense_replace_type_function.h"
#include "dense_cell_range_function.h"
#include "dense_lambda_peek_function.h"
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/node_tools.h>
#include <vespa/eval/eval/basic_nodes.h>
#include <vespa/eval/eval/operator_nodes.h>
#include <vespa/eval/eval/call_nodes.h>
#include <vespa/eval/eval/tensor_nodes.h>
#include <vespa/eval/eval/llvm/compile_cache.h>
#include <optional>
using namespace vespalib::eval;
using namespace vespalib::eval::nodes;
namespace vespalib::tensor {
namespace {
// 'simple peek': deterministic peek into a single parameter with
// compilable dimension index expressions.
const TensorPeek *find_simple_peek(const tensor_function::Lambda &lambda) {
const Function &function = lambda.lambda();
const size_t num_dims = lambda.result_type().dimensions().size();
auto peek = as<TensorPeek>(function.root());
if (peek && (function.num_params() == (num_dims + 1))) {
auto param = as<Symbol>(peek->get_child(0));
if (param && (param->id() == num_dims)) {
for (size_t i = 1; i < peek->num_children(); ++i) {
const Node &dim_expr = peek->get_child(i);
if (NodeTools::min_num_params(dim_expr) > num_dims) {
return nullptr;
}
if (CompiledFunction::detect_issues(dim_expr)) {
return nullptr;
}
}
return peek;
}
}
return nullptr;
}
Node_UP make_dim_expr(const TensorPeek::Dim &src_dim) {
if (src_dim.second.is_expr()) {
return NodeTools::copy(*src_dim.second.expr);
} else {
return std::make_unique<Number>(as_number(src_dim.second.label));
}
}
template <typename OP>
Node_UP make_op(Node_UP a, Node_UP b) {
auto res = std::make_unique<OP>();
res->bind(std::move(a), std::move(b));
return res;
}
Node_UP make_floor(Node_UP a) {
auto res = std::make_unique<Floor>();
res->bind_next(std::move(a));
return res;
}
struct PeekAnalyzer {
std::vector<size_t> dst_dim_sizes;
std::vector<size_t> src_dim_sizes;
std::vector<CompiledFunction::UP> src_dim_funs;
std::shared_ptr<Function const> src_idx_fun;
struct CellRange {
size_t offset;
size_t length;
bool is_full(size_t num_cells) const {
return ((offset == 0) && (length == num_cells));
}
};
struct Result {
bool valid;
std::optional<CellRange> cell_range;
static Result simple(CellRange range) { return Result{true, range}; }
static Result complex() { return Result{true, std::nullopt}; }
static Result invalid() { return Result{false, std::nullopt}; }
};
PeekAnalyzer(const ValueType &dst_type, const ValueType &src_type,
const TensorPeek::DimList &dim_list)
{
for (const auto& dim: dst_type.dimensions()) {
dst_dim_sizes.push_back(dim.size);
}
for (const auto& dim: src_type.dimensions()) {
src_dim_sizes.push_back(dim.size);
}
Node_UP idx_expr;
size_t num_params = dst_dim_sizes.size();
for (size_t i = 0; i < dim_list.size(); ++i) {
auto dim_expr = make_dim_expr(dim_list[i]);
src_dim_funs.push_back(std::make_unique<CompiledFunction>(*dim_expr, num_params, PassParams::ARRAY));
if (i == 0) {
idx_expr = std::move(dim_expr);
} else {
idx_expr = make_floor(std::move(idx_expr));
idx_expr = make_op<Mul>(std::move(idx_expr), std::make_unique<Number>(src_dim_sizes[i]));
idx_expr = make_op<Add>(std::move(idx_expr), std::move(dim_expr));
}
}
src_idx_fun = Function::create(std::move(idx_expr), dst_type.dimension_names());
}
bool step_params(std::vector<double> ¶ms) {
for (size_t idx = params.size(); idx-- > 0; ) {
if (size_t(params[idx] += 1.0) < dst_dim_sizes[idx]) {
return true;
} else {
params[idx] = 0.0;
}
}
return false;
}
size_t calculate_index(const std::vector<size_t> &src_address) {
size_t result = 0;
for (size_t i = 0; i < src_address.size(); ++i) {
result *= src_dim_sizes[i];
result += src_address[i];
}
return result;
}
Result analyze_indexes() {
CellRange range{0,0};
bool is_complex = false;
std::vector<double> params(dst_dim_sizes.size(), 0.0);
std::vector<size_t> src_address(src_dim_sizes.size(), 0);
do {
for (size_t i = 0; i < src_dim_funs.size(); ++i) {
auto dim_fun = src_dim_funs[i]->get_function();
size_t dim_idx = dim_fun(¶ms[0]);
if (dim_idx >= src_dim_sizes[i]) {
return Result::invalid();
}
src_address[i] = dim_idx;
}
size_t idx = calculate_index(src_address);
if (range.length == 0) {
range.offset = idx;
}
if (idx == (range.offset + range.length)) {
++range.length;
} else {
is_complex = true;
}
} while(step_params(params));
if (is_complex) {
return Result::complex();
}
return Result::simple(range);
}
};
} // namespace vespalib::tensor::<unnamed>
const TensorFunction &
DenseLambdaPeekOptimizer::optimize(const TensorFunction &expr, Stash &stash)
{
if (auto lambda = as<tensor_function::Lambda>(expr)) {
if (auto peek = find_simple_peek(*lambda)) {
const ValueType &dst_type = lambda->result_type();
const ValueType &src_type = lambda->types().get_type(peek->param());
if (src_type.is_dense()) {
assert(lambda->bindings().size() == 1);
assert(src_type.dimensions().size() == peek->dim_list().size());
size_t param_idx = lambda->bindings()[0];
PeekAnalyzer analyzer(dst_type, src_type, peek->dim_list());
auto result = analyzer.analyze_indexes();
if (result.valid) {
const auto &get_param = tensor_function::inject(src_type, param_idx, stash);
if (result.cell_range && (dst_type.cell_type() == src_type.cell_type())) {
auto cell_range = result.cell_range.value();
if (cell_range.is_full(src_type.dense_subspace_size())) {
return DenseReplaceTypeFunction::create_compact(dst_type, get_param, stash);
} else {
return stash.create<DenseCellRangeFunction>(dst_type, get_param,
cell_range.offset, cell_range.length);
}
} else {
return stash.create<DenseLambdaPeekFunction>(dst_type, get_param,
std::move(analyzer.src_idx_fun));
}
}
}
}
}
return expr;
}
} // namespace vespalib::tensor
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2018, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(MBED_CONF_RTOS_PRESENT)
#error [NOT_SUPPORTED] dns test cases require a RTOS to run.
#else
#define WIFI 2
#if !defined(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE) || \
(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == WIFI && !defined(MBED_CONF_NSAPI_DEFAULT_WIFI_SSID))
#error [NOT_SUPPORTED] No network configuration found for this target.
#else
#include "mbed.h"
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
#include "nsapi_dns.h"
#include "events/EventQueue.h"
#include "dns_tests.h"
#include "ip6string.h"
using namespace utest::v1;
namespace {
NetworkInterface *net;
}
const char dns_test_hosts[MBED_CONF_APP_DNS_TEST_HOSTS_NUM][DNS_TEST_HOST_LEN] = MBED_CONF_APP_DNS_TEST_HOSTS;
const char dns_test_hosts_second[MBED_CONF_APP_DNS_TEST_HOSTS_NUM][DNS_TEST_HOST_LEN] = MBED_CONF_APP_DNS_TEST_HOSTS_SECOND;
const char dns_test_hosts_multi_ip[MBED_CONF_APP_DNS_SIMULT_QUERIES][DNS_TEST_HOST_LEN] = MBED_CONF_APP_DNS_TEST_MULTI_IP_HOSTS;
// Callback used for asynchronous DNS result
void hostbyname_cb(void *data, nsapi_error_t result, SocketAddress *address)
{
dns_application_data *app_data = static_cast<dns_application_data *>(data);
app_data->result = result;
if (address) {
app_data->addr = *address;
}
app_data->semaphore->release();
app_data->value_set = true;
}
// General function to do asynchronous DNS host name resolution
void do_asynchronous_gethostbyname(const char hosts[][DNS_TEST_HOST_LEN], unsigned int op_count, int *exp_ok, int *exp_no_mem, int *exp_dns_failure, int *exp_timeout)
{
// Verify that there is enough hosts in the host list
TEST_ASSERT(op_count <= MBED_CONF_APP_DNS_TEST_HOSTS_NUM)
// Reset counters
(*exp_ok) = 0;
(*exp_no_mem) = 0;
(*exp_dns_failure) = 0;
(*exp_timeout) = 0;
// Create callback semaphore and data
rtos::Semaphore semaphore;
dns_application_data *data = new dns_application_data[op_count];
unsigned int count = 0;
for (unsigned int i = 0; i < op_count; i++) {
data[i].semaphore = &semaphore;
nsapi_error_t err = net->gethostbyname_async(hosts[i], mbed::Callback<void(nsapi_error_t, SocketAddress *)>(hostbyname_cb, (void *) &data[i]));
TEST_ASSERT(err >= 0 || err == NSAPI_ERROR_NO_MEMORY || err == NSAPI_ERROR_BUSY);
if (err >= 0) {
// Callback will be called
count++;
} else {
// No memory to initiate DNS query, callback will not be called
data[i].result = err;
}
}
// Wait for callback(s) to complete
for (unsigned int i = 0; i < count; i++) {
semaphore.acquire();
}
// Print result
for (unsigned int i = 0; i < op_count; i++) {
TEST_ASSERT(data[i].result > 0 || data[i].result == NSAPI_ERROR_NO_MEMORY || data[i].result == NSAPI_ERROR_BUSY || data[i].result == NSAPI_ERROR_DNS_FAILURE || data[i].result == NSAPI_ERROR_TIMEOUT);
if (data[i].result > 0) {
(*exp_ok)++;
tr_info("DNS: query \"%s\" => \"%s\"",
hosts[i], data[i].addr.get_ip_address());
} else if (data[i].result == NSAPI_ERROR_DNS_FAILURE) {
(*exp_dns_failure)++;
tr_error("DNS: query \"%s\" => DNS failure", hosts[i]);
} else if (data[i].result == NSAPI_ERROR_TIMEOUT) {
(*exp_timeout)++;
tr_error("DNS: query \"%s\" => timeout", hosts[i]);
} else if (data[i].result == NSAPI_ERROR_NO_MEMORY) {
(*exp_no_mem)++;
tr_error("DNS: query \"%s\" => no memory", hosts[i]);
} else if (data[i].result == NSAPI_ERROR_BUSY) {
(*exp_no_mem)++;
tr_error("DNS: query \"%s\" => busy", hosts[i]);
}
}
delete[] data;
}
void do_gethostbyname(const char hosts[][DNS_TEST_HOST_LEN], unsigned int op_count, int *exp_ok, int *exp_no_mem, int *exp_dns_failure, int *exp_timeout)
{
// Verify that there is enough hosts in the host list
TEST_ASSERT(op_count <= MBED_CONF_APP_DNS_TEST_HOSTS_NUM)
// Reset counters
(*exp_ok) = 0;
(*exp_no_mem) = 0;
(*exp_dns_failure) = 0;
(*exp_timeout) = 0;
for (unsigned int i = 0; i < op_count; i++) {
SocketAddress address;
nsapi_error_t err = net->gethostbyname(hosts[i], &address);
if (err == NSAPI_ERROR_OK) {
(*exp_ok)++;
tr_info("DNS: query \"%s\" => \"%s\"",
hosts[i], address.get_ip_address());
} else if (err == NSAPI_ERROR_DNS_FAILURE) {
(*exp_dns_failure)++;
tr_error("DNS: query \"%s\" => DNS failure", hosts[i]);
} else if (err == NSAPI_ERROR_TIMEOUT) {
(*exp_timeout)++;
tr_error("DNS: query \"%s\" => timeout", hosts[i]);
} else if (err == NSAPI_ERROR_NO_MEMORY) {
(*exp_no_mem)++;
tr_error("DNS: query \"%s\" => no memory", hosts[i]);
} else if (err == NSAPI_ERROR_BUSY) {
(*exp_no_mem)++;
tr_error("DNS: query \"%s\" => busy", hosts[i]);
} else {
tr_error("DNS: query \"%s\" => %d, unexpected answer", hosts[i], err);
TEST_ASSERT(err == NSAPI_ERROR_OK || err == NSAPI_ERROR_NO_MEMORY || err == NSAPI_ERROR_BUSY || err == NSAPI_ERROR_DNS_FAILURE || err == NSAPI_ERROR_TIMEOUT);
}
}
}
NetworkInterface *get_interface()
{
return net;
}
static void net_bringup()
{
nsapi_dns_reset();
MBED_ASSERT(MBED_CONF_APP_DNS_TEST_HOSTS_NUM >= MBED_CONF_NSAPI_DNS_CACHE_SIZE && MBED_CONF_APP_DNS_TEST_HOSTS_NUM >= MBED_CONF_APP_DNS_SIMULT_QUERIES + 1);
net = NetworkInterface::get_default_instance();
nsapi_error_t err = net->connect();
TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, err);
SocketAddress address;
net->get_ip_address(&address);
#define MESH 3
#if MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == MESH
printf("Waiting for GLOBAL_UP\n");
while (net->get_connection_status() != NSAPI_STATUS_GLOBAL_UP) {
ThisThread::sleep_for(500);
}
#endif
printf("MBED: IP address is '%s'\n", address ? address.get_ip_address() : "null");
}
static void net_bringdown()
{
NetworkInterface::get_default_instance()->disconnect();
tr_info("MBED: ifdown");
}
// Test setup
utest::v1::status_t test_setup(const size_t number_of_cases)
{
GREENTEA_SETUP(dns_global::TESTS_TIMEOUT, "default_auto");
net_bringup();
return verbose_test_setup_handler(number_of_cases);
}
void greentea_teardown(const size_t passed, const size_t failed, const failure_t failure)
{
net_bringdown();
return greentea_test_teardown_handler(passed, failed, failure);
}
Case cases[] = {
Case("ASYNCHRONOUS_DNS", ASYNCHRONOUS_DNS),
Case("ASYNCHRONOUS_DNS_SIMULTANEOUS", ASYNCHRONOUS_DNS_SIMULTANEOUS),
Case("ASYNCHRONOUS_DNS_SIMULTANEOUS_CACHE", ASYNCHRONOUS_DNS_SIMULTANEOUS_CACHE),
Case("SYNCHRONOUS_DNS_CACHE", SYNCHRONOUS_DNS_CACHE),
#ifndef MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES
Case("ASYNCHRONOUS_DNS_CACHE", ASYNCHRONOUS_DNS_CACHE),
#endif
#if !defined MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES || MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES > MBED_CONF_APP_DNS_TEST_HOSTS_NUM
Case("ASYNCHRONOUS_DNS_NON_ASYNC_AND_ASYNC", ASYNCHRONOUS_DNS_NON_ASYNC_AND_ASYNC),
#endif
Case("ASYNCHRONOUS_DNS_CANCEL", ASYNCHRONOUS_DNS_CANCEL),
#ifndef MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES
Case("ASYNCHRONOUS_DNS_EXTERNAL_EVENT_QUEUE", ASYNCHRONOUS_DNS_EXTERNAL_EVENT_QUEUE),
Case("ASYNCHRONOUS_DNS_INVALID_HOST", ASYNCHRONOUS_DNS_INVALID_HOST),
Case("ASYNCHRONOUS_DNS_TIMEOUTS", ASYNCHRONOUS_DNS_TIMEOUTS),
#endif
Case("ASYNCHRONOUS_DNS_SIMULTANEOUS_REPEAT", ASYNCHRONOUS_DNS_SIMULTANEOUS_REPEAT),
Case("SYNCHRONOUS_DNS", SYNCHRONOUS_DNS),
Case("SYNCHRONOUS_DNS_MULTIPLE", SYNCHRONOUS_DNS_MULTIPLE),
Case("SYNCHRONOUS_DNS_INVALID", SYNCHRONOUS_DNS_INVALID),
Case("SYNCHRONOUS_DNS_MULTI_IP", SYNCHRONOUS_DNS_MULTI_IP),
Case("ASYNCHRONOUS_DNS_MULTI_IP", ASYNCHRONOUS_DNS_MULTI_IP),
};
Specification specification(test_setup, cases, greentea_teardown, greentea_continue_handlers);
int main()
{
return !Harness::run(specification);
}
#endif // !defined(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE) || (MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == WIFI && !defined(MBED_CONF_NSAPI_DEFAULT_WIFI_SSID))
#endif // !defined(MBED_CONF_RTOS_PRESENT)
<commit_msg>Enable SYNCHRONOUS_DNS_CACHE just for NSAPI_PPP_AVAILABLE<commit_after>/*
* Copyright (c) 2018, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(MBED_CONF_RTOS_PRESENT)
#error [NOT_SUPPORTED] dns test cases require a RTOS to run.
#else
#define WIFI 2
#if !defined(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE) || \
(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == WIFI && !defined(MBED_CONF_NSAPI_DEFAULT_WIFI_SSID))
#error [NOT_SUPPORTED] No network configuration found for this target.
#else
#include "mbed.h"
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
#include "nsapi_dns.h"
#include "events/EventQueue.h"
#include "dns_tests.h"
#include "ip6string.h"
using namespace utest::v1;
namespace {
NetworkInterface *net;
}
const char dns_test_hosts[MBED_CONF_APP_DNS_TEST_HOSTS_NUM][DNS_TEST_HOST_LEN] = MBED_CONF_APP_DNS_TEST_HOSTS;
const char dns_test_hosts_second[MBED_CONF_APP_DNS_TEST_HOSTS_NUM][DNS_TEST_HOST_LEN] = MBED_CONF_APP_DNS_TEST_HOSTS_SECOND;
const char dns_test_hosts_multi_ip[MBED_CONF_APP_DNS_SIMULT_QUERIES][DNS_TEST_HOST_LEN] = MBED_CONF_APP_DNS_TEST_MULTI_IP_HOSTS;
// Callback used for asynchronous DNS result
void hostbyname_cb(void *data, nsapi_error_t result, SocketAddress *address)
{
dns_application_data *app_data = static_cast<dns_application_data *>(data);
app_data->result = result;
if (address) {
app_data->addr = *address;
}
app_data->semaphore->release();
app_data->value_set = true;
}
// General function to do asynchronous DNS host name resolution
void do_asynchronous_gethostbyname(const char hosts[][DNS_TEST_HOST_LEN], unsigned int op_count, int *exp_ok, int *exp_no_mem, int *exp_dns_failure, int *exp_timeout)
{
// Verify that there is enough hosts in the host list
TEST_ASSERT(op_count <= MBED_CONF_APP_DNS_TEST_HOSTS_NUM)
// Reset counters
(*exp_ok) = 0;
(*exp_no_mem) = 0;
(*exp_dns_failure) = 0;
(*exp_timeout) = 0;
// Create callback semaphore and data
rtos::Semaphore semaphore;
dns_application_data *data = new dns_application_data[op_count];
unsigned int count = 0;
for (unsigned int i = 0; i < op_count; i++) {
data[i].semaphore = &semaphore;
nsapi_error_t err = net->gethostbyname_async(hosts[i], mbed::Callback<void(nsapi_error_t, SocketAddress *)>(hostbyname_cb, (void *) &data[i]));
TEST_ASSERT(err >= 0 || err == NSAPI_ERROR_NO_MEMORY || err == NSAPI_ERROR_BUSY);
if (err >= 0) {
// Callback will be called
count++;
} else {
// No memory to initiate DNS query, callback will not be called
data[i].result = err;
}
}
// Wait for callback(s) to complete
for (unsigned int i = 0; i < count; i++) {
semaphore.acquire();
}
// Print result
for (unsigned int i = 0; i < op_count; i++) {
TEST_ASSERT(data[i].result > 0 || data[i].result == NSAPI_ERROR_NO_MEMORY || data[i].result == NSAPI_ERROR_BUSY || data[i].result == NSAPI_ERROR_DNS_FAILURE || data[i].result == NSAPI_ERROR_TIMEOUT);
if (data[i].result > 0) {
(*exp_ok)++;
tr_info("DNS: query \"%s\" => \"%s\"",
hosts[i], data[i].addr.get_ip_address());
} else if (data[i].result == NSAPI_ERROR_DNS_FAILURE) {
(*exp_dns_failure)++;
tr_error("DNS: query \"%s\" => DNS failure", hosts[i]);
} else if (data[i].result == NSAPI_ERROR_TIMEOUT) {
(*exp_timeout)++;
tr_error("DNS: query \"%s\" => timeout", hosts[i]);
} else if (data[i].result == NSAPI_ERROR_NO_MEMORY) {
(*exp_no_mem)++;
tr_error("DNS: query \"%s\" => no memory", hosts[i]);
} else if (data[i].result == NSAPI_ERROR_BUSY) {
(*exp_no_mem)++;
tr_error("DNS: query \"%s\" => busy", hosts[i]);
}
}
delete[] data;
}
void do_gethostbyname(const char hosts[][DNS_TEST_HOST_LEN], unsigned int op_count, int *exp_ok, int *exp_no_mem, int *exp_dns_failure, int *exp_timeout)
{
// Verify that there is enough hosts in the host list
TEST_ASSERT(op_count <= MBED_CONF_APP_DNS_TEST_HOSTS_NUM)
// Reset counters
(*exp_ok) = 0;
(*exp_no_mem) = 0;
(*exp_dns_failure) = 0;
(*exp_timeout) = 0;
for (unsigned int i = 0; i < op_count; i++) {
SocketAddress address;
nsapi_error_t err = net->gethostbyname(hosts[i], &address);
if (err == NSAPI_ERROR_OK) {
(*exp_ok)++;
tr_info("DNS: query \"%s\" => \"%s\"",
hosts[i], address.get_ip_address());
} else if (err == NSAPI_ERROR_DNS_FAILURE) {
(*exp_dns_failure)++;
tr_error("DNS: query \"%s\" => DNS failure", hosts[i]);
} else if (err == NSAPI_ERROR_TIMEOUT) {
(*exp_timeout)++;
tr_error("DNS: query \"%s\" => timeout", hosts[i]);
} else if (err == NSAPI_ERROR_NO_MEMORY) {
(*exp_no_mem)++;
tr_error("DNS: query \"%s\" => no memory", hosts[i]);
} else if (err == NSAPI_ERROR_BUSY) {
(*exp_no_mem)++;
tr_error("DNS: query \"%s\" => busy", hosts[i]);
} else {
tr_error("DNS: query \"%s\" => %d, unexpected answer", hosts[i], err);
TEST_ASSERT(err == NSAPI_ERROR_OK || err == NSAPI_ERROR_NO_MEMORY || err == NSAPI_ERROR_BUSY || err == NSAPI_ERROR_DNS_FAILURE || err == NSAPI_ERROR_TIMEOUT);
}
}
}
NetworkInterface *get_interface()
{
return net;
}
static void net_bringup()
{
nsapi_dns_reset();
MBED_ASSERT(MBED_CONF_APP_DNS_TEST_HOSTS_NUM >= MBED_CONF_NSAPI_DNS_CACHE_SIZE && MBED_CONF_APP_DNS_TEST_HOSTS_NUM >= MBED_CONF_APP_DNS_SIMULT_QUERIES + 1);
net = NetworkInterface::get_default_instance();
nsapi_error_t err = net->connect();
TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, err);
SocketAddress address;
net->get_ip_address(&address);
#define MESH 3
#if MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == MESH
printf("Waiting for GLOBAL_UP\n");
while (net->get_connection_status() != NSAPI_STATUS_GLOBAL_UP) {
ThisThread::sleep_for(500);
}
#endif
printf("MBED: IP address is '%s'\n", address ? address.get_ip_address() : "null");
}
static void net_bringdown()
{
NetworkInterface::get_default_instance()->disconnect();
tr_info("MBED: ifdown");
}
// Test setup
utest::v1::status_t test_setup(const size_t number_of_cases)
{
GREENTEA_SETUP(dns_global::TESTS_TIMEOUT, "default_auto");
net_bringup();
return verbose_test_setup_handler(number_of_cases);
}
void greentea_teardown(const size_t passed, const size_t failed, const failure_t failure)
{
net_bringdown();
return greentea_test_teardown_handler(passed, failed, failure);
}
Case cases[] = {
Case("ASYNCHRONOUS_DNS", ASYNCHRONOUS_DNS),
Case("ASYNCHRONOUS_DNS_SIMULTANEOUS", ASYNCHRONOUS_DNS_SIMULTANEOUS),
Case("ASYNCHRONOUS_DNS_SIMULTANEOUS_CACHE", ASYNCHRONOUS_DNS_SIMULTANEOUS_CACHE),
#if NSAPI_PPP_AVAILABLE
Case("SYNCHRONOUS_DNS_CACHE", SYNCHRONOUS_DNS_CACHE),
#endif
#ifndef MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES
Case("ASYNCHRONOUS_DNS_CACHE", ASYNCHRONOUS_DNS_CACHE),
#endif
#if !defined MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES || MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES > MBED_CONF_APP_DNS_TEST_HOSTS_NUM
Case("ASYNCHRONOUS_DNS_NON_ASYNC_AND_ASYNC", ASYNCHRONOUS_DNS_NON_ASYNC_AND_ASYNC),
#endif
Case("ASYNCHRONOUS_DNS_CANCEL", ASYNCHRONOUS_DNS_CANCEL),
#ifndef MBED_CONF_CELLULAR_OFFLOAD_DNS_QUERIES
Case("ASYNCHRONOUS_DNS_EXTERNAL_EVENT_QUEUE", ASYNCHRONOUS_DNS_EXTERNAL_EVENT_QUEUE),
Case("ASYNCHRONOUS_DNS_INVALID_HOST", ASYNCHRONOUS_DNS_INVALID_HOST),
Case("ASYNCHRONOUS_DNS_TIMEOUTS", ASYNCHRONOUS_DNS_TIMEOUTS),
#endif
Case("ASYNCHRONOUS_DNS_SIMULTANEOUS_REPEAT", ASYNCHRONOUS_DNS_SIMULTANEOUS_REPEAT),
Case("SYNCHRONOUS_DNS", SYNCHRONOUS_DNS),
Case("SYNCHRONOUS_DNS_MULTIPLE", SYNCHRONOUS_DNS_MULTIPLE),
Case("SYNCHRONOUS_DNS_INVALID", SYNCHRONOUS_DNS_INVALID),
Case("SYNCHRONOUS_DNS_MULTI_IP", SYNCHRONOUS_DNS_MULTI_IP),
Case("ASYNCHRONOUS_DNS_MULTI_IP", ASYNCHRONOUS_DNS_MULTI_IP),
};
Specification specification(test_setup, cases, greentea_teardown, greentea_continue_handlers);
int main()
{
return !Harness::run(specification);
}
#endif // !defined(MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE) || (MBED_CONF_TARGET_NETWORK_DEFAULT_INTERFACE_TYPE == WIFI && !defined(MBED_CONF_NSAPI_DEFAULT_WIFI_SSID))
#endif // !defined(MBED_CONF_RTOS_PRESENT)
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: defaulthelpprovider.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2006-12-15 02:01:43 $
*
* 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_extensions.hxx"
#include "defaulthelpprovider.hxx"
#include "pcrcommon.hxx"
#include "modulepcr.hxx"
/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_UCB_ALREADYINITIALIZEDEXCEPTION_HPP_
#include <com/sun/star/ucb/AlreadyInitializedException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XVCLWINDOWPEER_HPP_
#include <com/sun/star/awt/XVclWindowPeer.hpp>
#endif
/** === end UNO includes === **/
#include <toolkit/helper/vclunohelper.hxx>
#include <vcl/window.hxx>
#include <tools/diagnose_ex.h>
//------------------------------------------------------------------------
extern "C" void SAL_CALL createRegistryInfo_DefaultHelpProvider()
{
::pcr::OAutoRegistration< ::pcr::DefaultHelpProvider > aAutoRegistration;
}
//........................................................................
namespace pcr
{
//........................................................................
/** === begin UNO using === **/
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::XComponentContext;
using ::com::sun::star::inspection::XPropertyControl;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::inspection::XObjectInspectorUI;
using ::com::sun::star::uno::XInterface;
using ::com::sun::star::ucb::AlreadyInitializedException;
using ::com::sun::star::lang::IllegalArgumentException;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::awt::XWindow;
using ::com::sun::star::awt::XVclWindowPeer;
/** === end UNO using === **/
//====================================================================
//= DefaultHelpProvider
//====================================================================
//--------------------------------------------------------------------
DefaultHelpProvider::DefaultHelpProvider( const Reference< XComponentContext >& _rxContext )
:m_aContext( _rxContext )
,m_bConstructed( false )
{
}
//--------------------------------------------------------------------
DefaultHelpProvider::~DefaultHelpProvider()
{
}
//------------------------------------------------------------------------
::rtl::OUString DefaultHelpProvider::getImplementationName_static( ) throw(RuntimeException)
{
return ::rtl::OUString::createFromAscii( "org.openoffice.comp.extensions.DefaultHelpProvider");
}
//------------------------------------------------------------------------
Sequence< ::rtl::OUString > DefaultHelpProvider::getSupportedServiceNames_static( ) throw(RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(1);
aSupported[0] = ::rtl::OUString::createFromAscii( "com.sun.star.inspection.DefaultHelpProvider" );
return aSupported;
}
//------------------------------------------------------------------------
Reference< XInterface > SAL_CALL DefaultHelpProvider::Create( const Reference< XComponentContext >& _rxContext )
{
return *new DefaultHelpProvider( _rxContext );
}
//--------------------------------------------------------------------
void SAL_CALL DefaultHelpProvider::focusGained( const Reference< XPropertyControl >& _Control ) throw (RuntimeException)
{
if ( !m_xInspectorUI.is() )
throw RuntimeException( ::rtl::OUString(), *this );
try
{
m_xInspectorUI->setHelpSectionText( impl_getHelpText_nothrow( _Control ) );
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
}
//--------------------------------------------------------------------
void SAL_CALL DefaultHelpProvider::valueChanged( const Reference< XPropertyControl >& /*_Control*/ ) throw (RuntimeException)
{
// not interested in
}
//--------------------------------------------------------------------
void SAL_CALL DefaultHelpProvider::initialize( const Sequence< Any >& _arguments ) throw (Exception, RuntimeException)
{
if ( m_bConstructed )
throw AlreadyInitializedException();
StlSyntaxSequence< Any > arguments( _arguments );
if ( arguments.size() == 1 )
{ // constructor: "create( XObjectInspectorUI )"
Reference< XObjectInspectorUI > xUI( arguments[0], UNO_QUERY );
create( xUI );
return;
}
throw IllegalArgumentException( ::rtl::OUString(), *this, 0 );
}
//--------------------------------------------------------------------
void DefaultHelpProvider::create( const Reference< XObjectInspectorUI >& _rxUI )
{
if ( !_rxUI.is() )
throw IllegalArgumentException( ::rtl::OUString(), *this, 1 );
try
{
m_xInspectorUI = _rxUI;
m_xInspectorUI->registerControlObserver( this );
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
m_bConstructed = true;
}
//--------------------------------------------------------------------
Window* DefaultHelpProvider::impl_getVclControlWindow_nothrow( const Reference< XPropertyControl >& _rxControl )
{
Window* pControlWindow = NULL;
OSL_PRECOND( _rxControl.is(), "DefaultHelpProvider::impl_getVclControlWindow_nothrow: illegal control!" );
if ( !_rxControl.is() )
return pControlWindow;
try
{
Reference< XWindow > xControlWindow( _rxControl->getControlWindow(), UNO_QUERY_THROW );
pControlWindow = VCLUnoHelper::GetWindow( xControlWindow );
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
return pControlWindow;
}
//--------------------------------------------------------------------
::rtl::OUString DefaultHelpProvider::impl_getHelpText_nothrow( const Reference< XPropertyControl >& _rxControl )
{
::rtl::OUString sHelpText;
OSL_PRECOND( _rxControl.is(), "DefaultHelpProvider::impl_getHelpText_nothrow: illegal control!" );
if ( !_rxControl.is() )
return sHelpText;
Window* pControlWindow( impl_getVclControlWindow_nothrow( _rxControl ) );
OSL_ENSURE( pControlWindow, "DefaultHelpProvider::impl_getHelpText_nothrow: could not determine the VCL window!" );
if ( !pControlWindow )
return sHelpText;
sHelpText = pControlWindow->GetHelpText();
return sHelpText;
}
//........................................................................
} // namespace pcr
//........................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.3.222); FILE MERGED 2008/04/01 12:29:48 thb 1.3.222.2: #i85898# Stripping all external header guards 2008/03/31 12:31:40 rt 1.3.222.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: defaulthelpprovider.cxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_extensions.hxx"
#include "defaulthelpprovider.hxx"
#include "pcrcommon.hxx"
#include "modulepcr.hxx"
/** === begin UNO includes === **/
#include <com/sun/star/ucb/AlreadyInitializedException.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/awt/XVclWindowPeer.hpp>
/** === end UNO includes === **/
#include <toolkit/helper/vclunohelper.hxx>
#include <vcl/window.hxx>
#include <tools/diagnose_ex.h>
//------------------------------------------------------------------------
extern "C" void SAL_CALL createRegistryInfo_DefaultHelpProvider()
{
::pcr::OAutoRegistration< ::pcr::DefaultHelpProvider > aAutoRegistration;
}
//........................................................................
namespace pcr
{
//........................................................................
/** === begin UNO using === **/
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::XComponentContext;
using ::com::sun::star::inspection::XPropertyControl;
using ::com::sun::star::uno::RuntimeException;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::inspection::XObjectInspectorUI;
using ::com::sun::star::uno::XInterface;
using ::com::sun::star::ucb::AlreadyInitializedException;
using ::com::sun::star::lang::IllegalArgumentException;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::awt::XWindow;
using ::com::sun::star::awt::XVclWindowPeer;
/** === end UNO using === **/
//====================================================================
//= DefaultHelpProvider
//====================================================================
//--------------------------------------------------------------------
DefaultHelpProvider::DefaultHelpProvider( const Reference< XComponentContext >& _rxContext )
:m_aContext( _rxContext )
,m_bConstructed( false )
{
}
//--------------------------------------------------------------------
DefaultHelpProvider::~DefaultHelpProvider()
{
}
//------------------------------------------------------------------------
::rtl::OUString DefaultHelpProvider::getImplementationName_static( ) throw(RuntimeException)
{
return ::rtl::OUString::createFromAscii( "org.openoffice.comp.extensions.DefaultHelpProvider");
}
//------------------------------------------------------------------------
Sequence< ::rtl::OUString > DefaultHelpProvider::getSupportedServiceNames_static( ) throw(RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(1);
aSupported[0] = ::rtl::OUString::createFromAscii( "com.sun.star.inspection.DefaultHelpProvider" );
return aSupported;
}
//------------------------------------------------------------------------
Reference< XInterface > SAL_CALL DefaultHelpProvider::Create( const Reference< XComponentContext >& _rxContext )
{
return *new DefaultHelpProvider( _rxContext );
}
//--------------------------------------------------------------------
void SAL_CALL DefaultHelpProvider::focusGained( const Reference< XPropertyControl >& _Control ) throw (RuntimeException)
{
if ( !m_xInspectorUI.is() )
throw RuntimeException( ::rtl::OUString(), *this );
try
{
m_xInspectorUI->setHelpSectionText( impl_getHelpText_nothrow( _Control ) );
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
}
//--------------------------------------------------------------------
void SAL_CALL DefaultHelpProvider::valueChanged( const Reference< XPropertyControl >& /*_Control*/ ) throw (RuntimeException)
{
// not interested in
}
//--------------------------------------------------------------------
void SAL_CALL DefaultHelpProvider::initialize( const Sequence< Any >& _arguments ) throw (Exception, RuntimeException)
{
if ( m_bConstructed )
throw AlreadyInitializedException();
StlSyntaxSequence< Any > arguments( _arguments );
if ( arguments.size() == 1 )
{ // constructor: "create( XObjectInspectorUI )"
Reference< XObjectInspectorUI > xUI( arguments[0], UNO_QUERY );
create( xUI );
return;
}
throw IllegalArgumentException( ::rtl::OUString(), *this, 0 );
}
//--------------------------------------------------------------------
void DefaultHelpProvider::create( const Reference< XObjectInspectorUI >& _rxUI )
{
if ( !_rxUI.is() )
throw IllegalArgumentException( ::rtl::OUString(), *this, 1 );
try
{
m_xInspectorUI = _rxUI;
m_xInspectorUI->registerControlObserver( this );
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
m_bConstructed = true;
}
//--------------------------------------------------------------------
Window* DefaultHelpProvider::impl_getVclControlWindow_nothrow( const Reference< XPropertyControl >& _rxControl )
{
Window* pControlWindow = NULL;
OSL_PRECOND( _rxControl.is(), "DefaultHelpProvider::impl_getVclControlWindow_nothrow: illegal control!" );
if ( !_rxControl.is() )
return pControlWindow;
try
{
Reference< XWindow > xControlWindow( _rxControl->getControlWindow(), UNO_QUERY_THROW );
pControlWindow = VCLUnoHelper::GetWindow( xControlWindow );
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
return pControlWindow;
}
//--------------------------------------------------------------------
::rtl::OUString DefaultHelpProvider::impl_getHelpText_nothrow( const Reference< XPropertyControl >& _rxControl )
{
::rtl::OUString sHelpText;
OSL_PRECOND( _rxControl.is(), "DefaultHelpProvider::impl_getHelpText_nothrow: illegal control!" );
if ( !_rxControl.is() )
return sHelpText;
Window* pControlWindow( impl_getVclControlWindow_nothrow( _rxControl ) );
OSL_ENSURE( pControlWindow, "DefaultHelpProvider::impl_getHelpText_nothrow: could not determine the VCL window!" );
if ( !pControlWindow )
return sHelpText;
sHelpText = pControlWindow->GetHelpText();
return sHelpText;
}
//........................................................................
} // namespace pcr
//........................................................................
<|endoftext|> |
<commit_before>#include "sprite.h"
sprite::sprite(boolean isSolid, int xPosition, int yPosition)
{
xPosition=xPosition;
yPosition=yPosition;
isSolid=isSolid;
}
<commit_msg>Cleaning up redundant files.<commit_after><|endoftext|> |
<commit_before>/********************************************************************************
$Header$
purpose:
notes:
to do:
author(s):
- Dirk Farin, [email protected]
modifications:
24/Jan/2002 - Dirk Farin - Complete reimplementation based on old Image type.
02/Jun/1999 - Dirk Farin - first implementation
********************************************************************************
LibVideoGfx - video processing library
Copyright (C) 2002 Dirk Farin
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
********************************************************************************/
#ifndef LIBVIDEOGFX_GRAPHICS_BASIC_IMAGE_HH
#define LIBVIDEOGFX_GRAPHICS_BASIC_IMAGE_HH
#include <assert.h>
#include <libvideogfx/types.hh>
#include <libvideogfx/graphics/datatypes/bitmap.hh>
#include <algorithm>
namespace videogfx {
enum Colorspace
{
Colorspace_RGB, Colorspace_YUV, Colorspace_Greyscale, Colorspace_HSV,
Colorspace_Invalid
};
enum ChromaFormat
{
/** subsampling h:2 v:2 */ Chroma_420,
/** subsampling h:2 v:1 */ Chroma_422,
/** No subsampling */ Chroma_444,
Chroma_Invalid
};
enum BitmapChannel
{
Bitmap_Red = 0, Bitmap_Green = 1, Bitmap_Blue = 2,
Bitmap_Y = 0, Bitmap_Cb = 1, Bitmap_Cr = 2,
Bitmap_U = 1, Bitmap_V = 2,
Bitmap_Hue = 0, Bitmap_Saturation = 1, Bitmap_Value = 2,
Bitmap_Alpha=3
};
/** Check if chroma is horizontally subsampled. Usage of the more general #ChromaSubH()# is recommended. */
inline bool IsSubH(ChromaFormat cf) { return cf != Chroma_444; }
/** Check if chroma is vertically subsampled. Usage of the more general #ChromaSubV()# is recommended. */
inline bool IsSubV(ChromaFormat cf) { return cf == Chroma_420; }
/** Get horizontal subsampling factor. */
inline int ChromaSubH(ChromaFormat cf) { return (cf != Chroma_444) ? 2 : 1; }
/** Get vertical subsampling factor. */
inline int ChromaSubV(ChromaFormat cf) { return (cf == Chroma_420) ? 2 : 1; }
struct ImageParam
{
ImageParam() : width(0), height(0), halign(1), valign(1), border(0),
colorspace(Colorspace_Invalid), has_alpha(false),
chroma(Chroma_444), reduced_chroma_resolution(true),
chroma_border(-1), chroma_halign(-1), chroma_valign(-1)
{ }
int width,height;
int halign,valign;
int border;
Colorspace colorspace;
bool has_alpha;
ChromaFormat chroma;
bool reduced_chroma_resolution;
int chroma_border;
int chroma_halign;
int chroma_valign;
int AskChromaWidth() const
{
if (colorspace==Colorspace_YUV)
return (width +ChromaSubH(chroma)-1)/ChromaSubH(chroma);
else
return width;
}
int AskChromaHeight() const
{
if (colorspace==Colorspace_YUV)
return (height+ChromaSubV(chroma)-1)/ChromaSubV(chroma);
else
return height;
}
void AskChromaSizes(int& w,int &h) const;
int AskChromaBorder() const;
int AskChromaHAlign() const;
int AskChromaVAlign() const;
int BitmapWidth (BitmapChannel b) const { if (b==1||b==2) return AskChromaWidth(); else return width; }
int BitmapHeight(BitmapChannel b) const { if (b==1||b==2) return AskChromaHeight(); else return height; }
int ChromaScaleH(BitmapChannel b,int x) const
{ if ((b==1||b==2) && colorspace==Colorspace_YUV) return x/ChromaSubH(chroma); else return x; }
int ChromaScaleV(BitmapChannel b,int y) const
{ if ((b==1||b==2) && colorspace==Colorspace_YUV) return y/ChromaSubV(chroma); else return y; }
};
template <class Pel> class Image
{
public:
virtual ~Image() { }
void Create(const ImageParam&);
void Release();
/// Get colorspace independent image parameters.
ImageParam AskParam() const { return d_param; }
int AskWidth() const { return d_param.width; }
int AskHeight() const { return d_param.height; }
int AskBorder() const { return d_param.border; }
void GetSize(int& w,int& h) const { w=d_param.width; h=d_param.height; }
Bitmap<Pel>& AskBitmap(BitmapChannel pm_id) { return d_pm[pm_id]; }
const Bitmap<Pel>& AskBitmap(BitmapChannel pm_id) const { return d_pm[pm_id]; }
Pel*const* AskFrame(BitmapChannel pm_id) { return d_pm[pm_id].AskFrame(); }
const Pel*const* AskFrame(BitmapChannel pm_id) const { return d_pm[pm_id].AskFrame(); }
/** Replace a complete bitmap. Note that the new bitmap either has to be empty or has to
be exactly the same size as the old one.
Furthermore you are responsible that all alignments and the border size is sufficient
for your application. This is not checked!
If you insert or remove (by replacing a bitmap by an empty one) an alpha bitmap,
the alphamask-flag in ImageParam will be set accordingly.
*/
void ReplaceBitmap(BitmapChannel id,const Bitmap<Pel>&);
/// Set new image parameters.
void SetParam(const ImageParam& param) { d_param=param; }
Image<Pel> Clone() const;
Image<Pel> CreateSubView (int x0,int y0,int w,int h) const;
Image<Pel> CreateFieldView(bool top) const;
bool IsEmpty() const { return d_pm[0].IsEmpty(); }
Pel*const* AskFrameR() { return d_pm[Bitmap_Red].AskFrame(); }
const Pel*const* AskFrameR() const { return d_pm[Bitmap_Red].AskFrame(); }
Pel*const* AskFrameG() { return d_pm[Bitmap_Green].AskFrame(); }
const Pel*const* AskFrameG() const { return d_pm[Bitmap_Green].AskFrame(); }
Pel*const* AskFrameB() { return d_pm[Bitmap_Blue].AskFrame(); }
const Pel*const* AskFrameB() const { return d_pm[Bitmap_Blue].AskFrame(); }
Pel*const* AskFrameY() { return d_pm[Bitmap_Y].AskFrame(); }
const Pel*const* AskFrameY() const { return d_pm[Bitmap_Y].AskFrame(); }
Pel*const* AskFrameU() { return d_pm[Bitmap_U].AskFrame(); }
const Pel*const* AskFrameU() const { return d_pm[Bitmap_U].AskFrame(); }
Pel*const* AskFrameV() { return d_pm[Bitmap_V].AskFrame(); }
const Pel*const* AskFrameV() const { return d_pm[Bitmap_V].AskFrame(); }
Pel*const* AskFrameCb() { return d_pm[Bitmap_Cb].AskFrame(); }
const Pel*const* AskFrameCb() const { return d_pm[Bitmap_Cb].AskFrame(); }
Pel*const* AskFrameCr() { return d_pm[Bitmap_Cr].AskFrame(); }
const Pel*const* AskFrameCr() const { return d_pm[Bitmap_Cr].AskFrame(); }
Pel*const* AskFrameA() { return d_pm[Bitmap_Alpha].AskFrame(); }
const Pel*const* AskFrameA() const { return d_pm[Bitmap_Alpha].AskFrame(); }
Bitmap<Pel>& AskBitmapR() { return d_pm[Bitmap_Red]; }
const Bitmap<Pel>& AskBitmapR() const { return d_pm[Bitmap_Red]; }
Bitmap<Pel>& AskBitmapG() { return d_pm[Bitmap_Green]; }
const Bitmap<Pel>& AskBitmapG() const { return d_pm[Bitmap_Green]; }
Bitmap<Pel>& AskBitmapB() { return d_pm[Bitmap_Blue]; }
const Bitmap<Pel>& AskBitmapB() const { return d_pm[Bitmap_Blue]; }
Bitmap<Pel>& AskBitmapY() { return d_pm[Bitmap_Y]; }
const Bitmap<Pel>& AskBitmapY() const { return d_pm[Bitmap_Y]; }
Bitmap<Pel>& AskBitmapU() { return d_pm[Bitmap_U]; }
const Bitmap<Pel>& AskBitmapU() const { return d_pm[Bitmap_U]; }
Bitmap<Pel>& AskBitmapV() { return d_pm[Bitmap_V]; }
const Bitmap<Pel>& AskBitmapV() const { return d_pm[Bitmap_V]; }
Bitmap<Pel>& AskBitmapCb() { return d_pm[Bitmap_Cb]; }
const Bitmap<Pel>& AskBitmapCb() const { return d_pm[Bitmap_Cb]; }
Bitmap<Pel>& AskBitmapCr() { return d_pm[Bitmap_Cr]; }
const Bitmap<Pel>& AskBitmapCr() const { return d_pm[Bitmap_Cr]; }
Bitmap<Pel>& AskBitmapA() { return d_pm[Bitmap_Alpha]; }
const Bitmap<Pel>& AskBitmapA() const { return d_pm[Bitmap_Alpha]; }
bool IsShared() const
{
for (int i=0;i<4;i++)
if (d_pm[i].IsShared())
return true;
return false;
}
private:
Bitmap<Pel> d_pm[4];
ImageParam d_param;
};
template <class Pel> void Image<Pel>::Create(const ImageParam& param)
{
d_pm[0].Create(param.width, param.height, param.border,param.halign,param.valign);
switch (param.colorspace)
{
case Colorspace_RGB:
case Colorspace_HSV:
d_pm[1].Create(param.width, param.height, param.border,param.halign,param.valign);
d_pm[2].Create(param.width, param.height, param.border,param.halign,param.valign);
break;
case Colorspace_YUV:
if (param.reduced_chroma_resolution)
{
d_pm[1].Create(param.AskChromaWidth(), param.AskChromaHeight(), param.AskChromaBorder(),
param.AskChromaHAlign(),param.AskChromaVAlign());
d_pm[2].Create(param.AskChromaWidth(), param.AskChromaHeight(), param.AskChromaBorder(),
param.AskChromaHAlign(),param.AskChromaVAlign());
}
else
{
d_pm[1].Create(param.width, param.height, param.border,param.halign,param.valign);
d_pm[2].Create(param.width, param.height, param.border,param.halign,param.valign);
}
break;
case Colorspace_Greyscale:
d_pm[1].Release();
d_pm[2].Release();
break;
case Colorspace_Invalid:
Assert(0);
break;
}
if (param.has_alpha)
d_pm[Bitmap_Alpha].Create(param.width, param.height, param.border,param.halign,param.valign);
else
d_pm[Bitmap_Alpha].Release();
d_param = param;
}
template <class Pel> void Image<Pel>::Release()
{
for (int i=0;i<4;i++)
d_pm[i].Release();
d_param = ImageParam();
}
template <class Pel> Image<Pel> Image<Pel>::Clone() const
{
Image<Pel> img;
for (int i=0;i<4;i++)
img.d_pm[i] = d_pm[i].Clone();
img.d_param = d_param;
return img;
}
template <class Pel> Image<Pel> Image<Pel>::CreateSubView(int x0,int y0,int w,int h) const
{
Image<Pel> newimg;
newimg.d_param = d_param;
newimg.d_param.width = w;
newimg.d_param.height = h;
newimg.d_param.halign = 1;
newimg.d_param.valign = 1;
newimg.d_param.border = 0;
newimg.d_param.chroma_border = -1;
newimg.d_param.chroma_halign = -1;
newimg.d_param.chroma_valign = -1;
if (d_param.colorspace == Colorspace_YUV)
{
newimg.d_pm[0] = d_pm[0].CreateSubView(x0,y0,w,h);
newimg.d_pm[3] = d_pm[3].CreateSubView(x0,y0,w,h);
int subh = ChromaSubH(d_param.chroma);
int subv = ChromaSubV(d_param.chroma);
newimg.d_pm[1] = d_pm[1].CreateSubView(x0/subh,y0/subv,(w+subh-1)/subh,(h+subv-1)/subv);
newimg.d_pm[2] = d_pm[2].CreateSubView(x0/subh,y0/subv,(w+subh-1)/subh,(h+subv-1)/subv);
}
else
{
for (int i=0;i<4;i++)
newimg.d_pm[i] = d_pm[i].CreateSubView(x0,y0,w,h);
}
return newimg;
}
template <class Pel> Image<Pel> Image<Pel>::CreateFieldView(bool top) const
{
if (!top && d_param.colorspace==Colorspace_YUV && d_param.chroma==Chroma_420 &&
(d_pm[0].AskHeight()%2)==0 && (d_pm[1].AskHeight()%2)==1)
{
AssertDescr(false,"not enough chroma information for bottom field");
}
Image<Pel> newimg;
newimg.d_param = d_param;
for (int i=0;i<4;i++)
newimg.d_pm[i] = d_pm[i].CreateFieldView(top);
newimg.d_param.width = newimg.d_pm[0].AskWidth();
newimg.d_param.height = newimg.d_pm[0].AskHeight();
newimg.d_param.halign = 1;
newimg.d_param.valign = 1;
newimg.d_param.border = 0;
newimg.d_param.chroma_border = -1;
newimg.d_param.chroma_halign = -1;
newimg.d_param.chroma_valign = -1;
return newimg;
}
}
#endif
<commit_msg>exchanged ImageParam initialization because of name-clash to ncurses library<commit_after>/********************************************************************************
$Header$
purpose:
notes:
to do:
author(s):
- Dirk Farin, [email protected]
modifications:
24/Jan/2002 - Dirk Farin - Complete reimplementation based on old Image type.
02/Jun/1999 - Dirk Farin - first implementation
********************************************************************************
LibVideoGfx - video processing library
Copyright (C) 2002 Dirk Farin
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
********************************************************************************/
#ifndef LIBVIDEOGFX_GRAPHICS_BASIC_IMAGE_HH
#define LIBVIDEOGFX_GRAPHICS_BASIC_IMAGE_HH
#include <assert.h>
#include <libvideogfx/types.hh>
#include <libvideogfx/graphics/datatypes/bitmap.hh>
#include <algorithm>
namespace videogfx {
enum Colorspace
{
Colorspace_RGB, Colorspace_YUV, Colorspace_Greyscale, Colorspace_HSV,
Colorspace_Invalid
};
enum ChromaFormat
{
/** subsampling h:2 v:2 */ Chroma_420,
/** subsampling h:2 v:1 */ Chroma_422,
/** No subsampling */ Chroma_444,
Chroma_Invalid
};
enum BitmapChannel
{
Bitmap_Red = 0, Bitmap_Green = 1, Bitmap_Blue = 2,
Bitmap_Y = 0, Bitmap_Cb = 1, Bitmap_Cr = 2,
Bitmap_U = 1, Bitmap_V = 2,
Bitmap_Hue = 0, Bitmap_Saturation = 1, Bitmap_Value = 2,
Bitmap_Alpha=3
};
/** Check if chroma is horizontally subsampled. Usage of the more general #ChromaSubH()# is recommended. */
inline bool IsSubH(ChromaFormat cf) { return cf != Chroma_444; }
/** Check if chroma is vertically subsampled. Usage of the more general #ChromaSubV()# is recommended. */
inline bool IsSubV(ChromaFormat cf) { return cf == Chroma_420; }
/** Get horizontal subsampling factor. */
inline int ChromaSubH(ChromaFormat cf) { return (cf != Chroma_444) ? 2 : 1; }
/** Get vertical subsampling factor. */
inline int ChromaSubV(ChromaFormat cf) { return (cf == Chroma_420) ? 2 : 1; }
struct ImageParam
{
ImageParam() : width(0), height(0), halign(1), valign(1),
colorspace(Colorspace_Invalid), has_alpha(false),
chroma(Chroma_444), reduced_chroma_resolution(true),
chroma_border(-1), chroma_halign(-1), chroma_valign(-1)
{
border=0;
}
int width,height;
int halign,valign;
int border;
Colorspace colorspace;
bool has_alpha;
ChromaFormat chroma;
bool reduced_chroma_resolution;
int chroma_border;
int chroma_halign;
int chroma_valign;
int AskChromaWidth() const
{
if (colorspace==Colorspace_YUV)
return (width +ChromaSubH(chroma)-1)/ChromaSubH(chroma);
else
return width;
}
int AskChromaHeight() const
{
if (colorspace==Colorspace_YUV)
return (height+ChromaSubV(chroma)-1)/ChromaSubV(chroma);
else
return height;
}
void AskChromaSizes(int& w,int &h) const;
int AskChromaBorder() const;
int AskChromaHAlign() const;
int AskChromaVAlign() const;
int BitmapWidth (BitmapChannel b) const { if (b==1||b==2) return AskChromaWidth(); else return width; }
int BitmapHeight(BitmapChannel b) const { if (b==1||b==2) return AskChromaHeight(); else return height; }
int ChromaScaleH(BitmapChannel b,int x) const
{ if ((b==1||b==2) && colorspace==Colorspace_YUV) return x/ChromaSubH(chroma); else return x; }
int ChromaScaleV(BitmapChannel b,int y) const
{ if ((b==1||b==2) && colorspace==Colorspace_YUV) return y/ChromaSubV(chroma); else return y; }
};
template <class Pel> class Image
{
public:
virtual ~Image() { }
void Create(const ImageParam&);
void Release();
/// Get colorspace independent image parameters.
ImageParam AskParam() const { return d_param; }
int AskWidth() const { return d_param.width; }
int AskHeight() const { return d_param.height; }
int AskBorder() const { return d_param.border; }
void GetSize(int& w,int& h) const { w=d_param.width; h=d_param.height; }
Bitmap<Pel>& AskBitmap(BitmapChannel pm_id) { return d_pm[pm_id]; }
const Bitmap<Pel>& AskBitmap(BitmapChannel pm_id) const { return d_pm[pm_id]; }
Pel*const* AskFrame(BitmapChannel pm_id) { return d_pm[pm_id].AskFrame(); }
const Pel*const* AskFrame(BitmapChannel pm_id) const { return d_pm[pm_id].AskFrame(); }
/** Replace a complete bitmap. Note that the new bitmap either has to be empty or has to
be exactly the same size as the old one.
Furthermore you are responsible that all alignments and the border size is sufficient
for your application. This is not checked!
If you insert or remove (by replacing a bitmap by an empty one) an alpha bitmap,
the alphamask-flag in ImageParam will be set accordingly.
*/
void ReplaceBitmap(BitmapChannel id,const Bitmap<Pel>&);
/// Set new image parameters.
void SetParam(const ImageParam& param) { d_param=param; }
Image<Pel> Clone() const;
Image<Pel> CreateSubView (int x0,int y0,int w,int h) const;
Image<Pel> CreateFieldView(bool top) const;
bool IsEmpty() const { return d_pm[0].IsEmpty(); }
Pel*const* AskFrameR() { return d_pm[Bitmap_Red].AskFrame(); }
const Pel*const* AskFrameR() const { return d_pm[Bitmap_Red].AskFrame(); }
Pel*const* AskFrameG() { return d_pm[Bitmap_Green].AskFrame(); }
const Pel*const* AskFrameG() const { return d_pm[Bitmap_Green].AskFrame(); }
Pel*const* AskFrameB() { return d_pm[Bitmap_Blue].AskFrame(); }
const Pel*const* AskFrameB() const { return d_pm[Bitmap_Blue].AskFrame(); }
Pel*const* AskFrameY() { return d_pm[Bitmap_Y].AskFrame(); }
const Pel*const* AskFrameY() const { return d_pm[Bitmap_Y].AskFrame(); }
Pel*const* AskFrameU() { return d_pm[Bitmap_U].AskFrame(); }
const Pel*const* AskFrameU() const { return d_pm[Bitmap_U].AskFrame(); }
Pel*const* AskFrameV() { return d_pm[Bitmap_V].AskFrame(); }
const Pel*const* AskFrameV() const { return d_pm[Bitmap_V].AskFrame(); }
Pel*const* AskFrameCb() { return d_pm[Bitmap_Cb].AskFrame(); }
const Pel*const* AskFrameCb() const { return d_pm[Bitmap_Cb].AskFrame(); }
Pel*const* AskFrameCr() { return d_pm[Bitmap_Cr].AskFrame(); }
const Pel*const* AskFrameCr() const { return d_pm[Bitmap_Cr].AskFrame(); }
Pel*const* AskFrameA() { return d_pm[Bitmap_Alpha].AskFrame(); }
const Pel*const* AskFrameA() const { return d_pm[Bitmap_Alpha].AskFrame(); }
Bitmap<Pel>& AskBitmapR() { return d_pm[Bitmap_Red]; }
const Bitmap<Pel>& AskBitmapR() const { return d_pm[Bitmap_Red]; }
Bitmap<Pel>& AskBitmapG() { return d_pm[Bitmap_Green]; }
const Bitmap<Pel>& AskBitmapG() const { return d_pm[Bitmap_Green]; }
Bitmap<Pel>& AskBitmapB() { return d_pm[Bitmap_Blue]; }
const Bitmap<Pel>& AskBitmapB() const { return d_pm[Bitmap_Blue]; }
Bitmap<Pel>& AskBitmapY() { return d_pm[Bitmap_Y]; }
const Bitmap<Pel>& AskBitmapY() const { return d_pm[Bitmap_Y]; }
Bitmap<Pel>& AskBitmapU() { return d_pm[Bitmap_U]; }
const Bitmap<Pel>& AskBitmapU() const { return d_pm[Bitmap_U]; }
Bitmap<Pel>& AskBitmapV() { return d_pm[Bitmap_V]; }
const Bitmap<Pel>& AskBitmapV() const { return d_pm[Bitmap_V]; }
Bitmap<Pel>& AskBitmapCb() { return d_pm[Bitmap_Cb]; }
const Bitmap<Pel>& AskBitmapCb() const { return d_pm[Bitmap_Cb]; }
Bitmap<Pel>& AskBitmapCr() { return d_pm[Bitmap_Cr]; }
const Bitmap<Pel>& AskBitmapCr() const { return d_pm[Bitmap_Cr]; }
Bitmap<Pel>& AskBitmapA() { return d_pm[Bitmap_Alpha]; }
const Bitmap<Pel>& AskBitmapA() const { return d_pm[Bitmap_Alpha]; }
bool IsShared() const
{
for (int i=0;i<4;i++)
if (d_pm[i].IsShared())
return true;
return false;
}
private:
Bitmap<Pel> d_pm[4];
ImageParam d_param;
};
template <class Pel> void Image<Pel>::Create(const ImageParam& param)
{
d_pm[0].Create(param.width, param.height, param.border,param.halign,param.valign);
switch (param.colorspace)
{
case Colorspace_RGB:
case Colorspace_HSV:
d_pm[1].Create(param.width, param.height, param.border,param.halign,param.valign);
d_pm[2].Create(param.width, param.height, param.border,param.halign,param.valign);
break;
case Colorspace_YUV:
if (param.reduced_chroma_resolution)
{
d_pm[1].Create(param.AskChromaWidth(), param.AskChromaHeight(), param.AskChromaBorder(),
param.AskChromaHAlign(),param.AskChromaVAlign());
d_pm[2].Create(param.AskChromaWidth(), param.AskChromaHeight(), param.AskChromaBorder(),
param.AskChromaHAlign(),param.AskChromaVAlign());
}
else
{
d_pm[1].Create(param.width, param.height, param.border,param.halign,param.valign);
d_pm[2].Create(param.width, param.height, param.border,param.halign,param.valign);
}
break;
case Colorspace_Greyscale:
d_pm[1].Release();
d_pm[2].Release();
break;
case Colorspace_Invalid:
Assert(0);
break;
}
if (param.has_alpha)
d_pm[Bitmap_Alpha].Create(param.width, param.height, param.border,param.halign,param.valign);
else
d_pm[Bitmap_Alpha].Release();
d_param = param;
}
template <class Pel> void Image<Pel>::Release()
{
for (int i=0;i<4;i++)
d_pm[i].Release();
d_param = ImageParam();
}
template <class Pel> Image<Pel> Image<Pel>::Clone() const
{
Image<Pel> img;
for (int i=0;i<4;i++)
img.d_pm[i] = d_pm[i].Clone();
img.d_param = d_param;
return img;
}
template <class Pel> Image<Pel> Image<Pel>::CreateSubView(int x0,int y0,int w,int h) const
{
Image<Pel> newimg;
newimg.d_param = d_param;
newimg.d_param.width = w;
newimg.d_param.height = h;
newimg.d_param.halign = 1;
newimg.d_param.valign = 1;
newimg.d_param.border = 0;
newimg.d_param.chroma_border = -1;
newimg.d_param.chroma_halign = -1;
newimg.d_param.chroma_valign = -1;
if (d_param.colorspace == Colorspace_YUV)
{
newimg.d_pm[0] = d_pm[0].CreateSubView(x0,y0,w,h);
newimg.d_pm[3] = d_pm[3].CreateSubView(x0,y0,w,h);
int subh = ChromaSubH(d_param.chroma);
int subv = ChromaSubV(d_param.chroma);
newimg.d_pm[1] = d_pm[1].CreateSubView(x0/subh,y0/subv,(w+subh-1)/subh,(h+subv-1)/subv);
newimg.d_pm[2] = d_pm[2].CreateSubView(x0/subh,y0/subv,(w+subh-1)/subh,(h+subv-1)/subv);
}
else
{
for (int i=0;i<4;i++)
newimg.d_pm[i] = d_pm[i].CreateSubView(x0,y0,w,h);
}
return newimg;
}
template <class Pel> Image<Pel> Image<Pel>::CreateFieldView(bool top) const
{
if (!top && d_param.colorspace==Colorspace_YUV && d_param.chroma==Chroma_420 &&
(d_pm[0].AskHeight()%2)==0 && (d_pm[1].AskHeight()%2)==1)
{
AssertDescr(false,"not enough chroma information for bottom field");
}
Image<Pel> newimg;
newimg.d_param = d_param;
for (int i=0;i<4;i++)
newimg.d_pm[i] = d_pm[i].CreateFieldView(top);
newimg.d_param.width = newimg.d_pm[0].AskWidth();
newimg.d_param.height = newimg.d_pm[0].AskHeight();
newimg.d_param.halign = 1;
newimg.d_param.valign = 1;
newimg.d_param.border = 0;
newimg.d_param.chroma_border = -1;
newimg.d_param.chroma_halign = -1;
newimg.d_param.chroma_valign = -1;
return newimg;
}
}
#endif
<|endoftext|> |
<commit_before>/**
* This file is part of TelepathyQt
*
* @copyright Copyright (C) 2012 Collabora Ltd. <http://www.collabora.co.uk/>
* @copyright Copyright (C) 2012 Nokia Corporation
* @license LGPL 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt/DBusService>
#include "TelepathyQt/_gen/dbus-service.moc.hpp"
#include "TelepathyQt/debug-internal.h"
#include <TelepathyQt/Constants>
#include <TelepathyQt/DBusObject>
#include <QDBusConnection>
#include <QString>
namespace Tp
{
struct TP_QT_NO_EXPORT DBusService::Private
{
Private(DBusService *parent, const QDBusConnection &dbusConnection)
: parent(parent),
dbusObject(new DBusObject(dbusConnection, parent)),
registered(false)
{
}
DBusService *parent;
QString busName;
QString objectPath;
DBusObject *dbusObject;
bool registered;
};
/**
* \class DBusService
* \ingroup servicesideimpl
* \headerfile TelepathyQt/dbus-service.h <TelepathyQt/DBusService>
*
* \brief Base class for D-Bus services.
*
* This class serves as a base for all the classes that are used to implement
* D-Bus services.
*/
/**
* Construct a DBusService that uses the given \a dbusConnection.
*
* \param dbusConnection The D-Bus connection that will be used by this service.
*/
DBusService::DBusService(const QDBusConnection &dbusConnection)
: mPriv(new Private(this, dbusConnection))
{
}
/**
* Class destructor.
*/
DBusService::~DBusService()
{
delete mPriv;
}
/**
* Return the D-Bus connection associated with this service.
*
* \return the D-Bus connection associated with this service.
*/
QDBusConnection DBusService::dbusConnection() const
{
return mPriv->dbusObject->dbusConnection();
}
/**
* Return the D-Bus service name of this service.
*
* This is only valid after this service has been registered
* on the bus using registerObject().
*
* \return the D-Bus service name of this service.
*/
QString DBusService::busName() const
{
return mPriv->busName;
}
/**
* Return the D-Bus object path of this service.
*
* This is only valid after this service has been registered
* on the bus using registerObject().
*
* \return the D-Bus object path of this service.
*/
QString DBusService::objectPath() const
{
return mPriv->objectPath;
}
/**
* Return the DBusObject that is used for registering this service on the bus.
*
* The DBusObject is the object on which all the interface adaptors
* for this service are plugged.
*
* \return a pointer to the DBusObject that is used for registering
* this service on the bus.
*/
DBusObject *DBusService::dbusObject() const
{
return mPriv->dbusObject;
}
/**
* Return whether this D-Bus service has been registered on the bus or not.
*
* \return \c true if the service has been registered, or \c false otherwise.
*/
bool DBusService::isRegistered() const
{
return mPriv->registered;
}
/**
* Register this service object on the bus with the given \a busName and \a objectPath.
*
* \a error needs to be a valid pointer to a DBusError instance, where any
* possible D-Bus error will be stored.
*
* A service may only be registered once in its lifetime.
* Use isRegistered() to find out if it has already been registered or not.
*
* You normally don't need to use this method directly.
* Subclasses should provide a simplified version of it.
*
* \param busName The D-Bus service name of this object.
* \param objectPath The D-Bus object path of this object.
* \param error A pointer to a valid DBusError instance, where any
* possible D-Bus error will be stored.
* \return \c true on success or \c false otherwise.
*/
bool DBusService::registerObject(const QString &busName, const QString &objectPath,
DBusError *error)
{
if (mPriv->registered) {
return true;
}
if (!mPriv->dbusObject->dbusConnection().registerService(busName)) {
error->set(TP_QT_ERROR_INVALID_ARGUMENT,
QString(QLatin1String("Name %s already in use by another process"))
.arg(busName));
warning() << "Unable to register service" << busName <<
"- name already registered by another process";
return false;
}
if (!mPriv->dbusObject->dbusConnection().registerObject(objectPath, mPriv->dbusObject)) {
error->set(TP_QT_ERROR_INVALID_ARGUMENT,
QString(QLatin1String("Object at path %s already registered"))
.arg(objectPath));
warning() << "Unable to register object" << objectPath <<
"- path already registered";
return false;
}
debug() << "Registered object" << objectPath << "at bus name" << busName;
mPriv->busName = busName;
mPriv->objectPath = objectPath;
mPriv->registered = true;
return true;
}
/**
* \fn QVariantMap DBusService::immutableProperties() const
*
* Return the immutable properties of this D-Bus service object.
*
* Immutable properties cannot change after the object has been registered
* on the bus with registerObject().
*
* \return The immutable properties of this D-Bus service object.
*/
struct AbstractDBusServiceInterface::Private
{
Private(const QString &interfaceName)
: interfaceName(interfaceName),
dbusObject(0),
registered(false)
{
}
QString interfaceName;
DBusObject *dbusObject;
bool registered;
};
/**
* \class AbstractDBusServiceInterface
* \ingroup servicesideimpl
* \headerfile TelepathyQt/dbus-service.h <TelepathyQt/AbstractDBusServiceInterface>
*
* \brief Base class for D-Bus service interfaces.
*
* This class serves as a base for all the classes that are used to implement
* interfaces that sit on top of D-Bus services.
*/
/**
* Construct an AbstractDBusServiceInterface that implements
* the interface with the given \a interfaceName.
*
* \param interfaceName The name of the interface that this class implements.
*/
AbstractDBusServiceInterface::AbstractDBusServiceInterface(const QString &interfaceName)
: mPriv(new Private(interfaceName))
{
}
/**
* Class destructor.
*/
AbstractDBusServiceInterface::~AbstractDBusServiceInterface()
{
delete mPriv;
}
/**
* Return the name of the interface that this class implements,
* as given on the constructor.
*
* \return The name of the interface that this class implements.
*/
QString AbstractDBusServiceInterface::interfaceName() const
{
return mPriv->interfaceName;
}
/**
* Return the DBusObject on which the adaptor of this interface is plugged.
*
* This is only accessible after the interface has been registered
* with registerInterface().
*
* \return a pointer to the DBusObject on which the adaptor
* of this interface is plugged.
* \sa DBusService::dbusObject()
*/
DBusObject *AbstractDBusServiceInterface::dbusObject() const
{
return mPriv->dbusObject;
}
/**
* Return whether this interface has been registered.
*
* \return \c true if the service has been registered, or \c false otherwise.
* \sa registerInterface()
*/
bool AbstractDBusServiceInterface::isRegistered() const
{
return mPriv->registered;
}
/**
* Registers this interface by plugging its adaptor
* on the given \a dbusObject.
*
* \param dbusObject The object on which to plug the adaptor.
* \return \c false if the interface has already been registered,
* or \a true otherwise.
* \sa isRegistered()
*/
bool AbstractDBusServiceInterface::registerInterface(DBusObject *dbusObject)
{
if (mPriv->registered) {
return true;
}
mPriv->dbusObject = dbusObject;
createAdaptor();
mPriv->registered = true;
return true;
}
/**
* \fn QVariantMap AbstractDBusServiceInterface::immutableProperties() const
*
* Return the immutable properties of this interface.
*
* Immutable properties cannot change after the interface has been registered
* on a service on the bus with registerInterface().
*
* \return The immutable properties of this interface.
*/
/**
* \fn void AbstractDBusServiceInterface::createAdaptor()
*
* Create the adaptor for this interface.
*
* Subclasses should reimplement this appropriately.
*/
}
<commit_msg>DBusService: Fix QString args replacement in registerObject()<commit_after>/**
* This file is part of TelepathyQt
*
* @copyright Copyright (C) 2012 Collabora Ltd. <http://www.collabora.co.uk/>
* @copyright Copyright (C) 2012 Nokia Corporation
* @license LGPL 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt/DBusService>
#include "TelepathyQt/_gen/dbus-service.moc.hpp"
#include "TelepathyQt/debug-internal.h"
#include <TelepathyQt/Constants>
#include <TelepathyQt/DBusObject>
#include <QDBusConnection>
#include <QString>
namespace Tp
{
struct TP_QT_NO_EXPORT DBusService::Private
{
Private(DBusService *parent, const QDBusConnection &dbusConnection)
: parent(parent),
dbusObject(new DBusObject(dbusConnection, parent)),
registered(false)
{
}
DBusService *parent;
QString busName;
QString objectPath;
DBusObject *dbusObject;
bool registered;
};
/**
* \class DBusService
* \ingroup servicesideimpl
* \headerfile TelepathyQt/dbus-service.h <TelepathyQt/DBusService>
*
* \brief Base class for D-Bus services.
*
* This class serves as a base for all the classes that are used to implement
* D-Bus services.
*/
/**
* Construct a DBusService that uses the given \a dbusConnection.
*
* \param dbusConnection The D-Bus connection that will be used by this service.
*/
DBusService::DBusService(const QDBusConnection &dbusConnection)
: mPriv(new Private(this, dbusConnection))
{
}
/**
* Class destructor.
*/
DBusService::~DBusService()
{
delete mPriv;
}
/**
* Return the D-Bus connection associated with this service.
*
* \return the D-Bus connection associated with this service.
*/
QDBusConnection DBusService::dbusConnection() const
{
return mPriv->dbusObject->dbusConnection();
}
/**
* Return the D-Bus service name of this service.
*
* This is only valid after this service has been registered
* on the bus using registerObject().
*
* \return the D-Bus service name of this service.
*/
QString DBusService::busName() const
{
return mPriv->busName;
}
/**
* Return the D-Bus object path of this service.
*
* This is only valid after this service has been registered
* on the bus using registerObject().
*
* \return the D-Bus object path of this service.
*/
QString DBusService::objectPath() const
{
return mPriv->objectPath;
}
/**
* Return the DBusObject that is used for registering this service on the bus.
*
* The DBusObject is the object on which all the interface adaptors
* for this service are plugged.
*
* \return a pointer to the DBusObject that is used for registering
* this service on the bus.
*/
DBusObject *DBusService::dbusObject() const
{
return mPriv->dbusObject;
}
/**
* Return whether this D-Bus service has been registered on the bus or not.
*
* \return \c true if the service has been registered, or \c false otherwise.
*/
bool DBusService::isRegistered() const
{
return mPriv->registered;
}
/**
* Register this service object on the bus with the given \a busName and \a objectPath.
*
* \a error needs to be a valid pointer to a DBusError instance, where any
* possible D-Bus error will be stored.
*
* A service may only be registered once in its lifetime.
* Use isRegistered() to find out if it has already been registered or not.
*
* You normally don't need to use this method directly.
* Subclasses should provide a simplified version of it.
*
* \param busName The D-Bus service name of this object.
* \param objectPath The D-Bus object path of this object.
* \param error A pointer to a valid DBusError instance, where any
* possible D-Bus error will be stored.
* \return \c true on success or \c false otherwise.
*/
bool DBusService::registerObject(const QString &busName, const QString &objectPath,
DBusError *error)
{
if (mPriv->registered) {
return true;
}
if (!mPriv->dbusObject->dbusConnection().registerService(busName)) {
error->set(TP_QT_ERROR_INVALID_ARGUMENT,
QString(QLatin1String("Name %1 already in use by another process"))
.arg(busName));
warning() << "Unable to register service" << busName <<
"- name already registered by another process";
return false;
}
if (!mPriv->dbusObject->dbusConnection().registerObject(objectPath, mPriv->dbusObject)) {
error->set(TP_QT_ERROR_INVALID_ARGUMENT,
QString(QLatin1String("Object at path %1 already registered"))
.arg(objectPath));
warning() << "Unable to register object" << objectPath <<
"- path already registered";
return false;
}
debug() << "Registered object" << objectPath << "at bus name" << busName;
mPriv->busName = busName;
mPriv->objectPath = objectPath;
mPriv->registered = true;
return true;
}
/**
* \fn QVariantMap DBusService::immutableProperties() const
*
* Return the immutable properties of this D-Bus service object.
*
* Immutable properties cannot change after the object has been registered
* on the bus with registerObject().
*
* \return The immutable properties of this D-Bus service object.
*/
struct AbstractDBusServiceInterface::Private
{
Private(const QString &interfaceName)
: interfaceName(interfaceName),
dbusObject(0),
registered(false)
{
}
QString interfaceName;
DBusObject *dbusObject;
bool registered;
};
/**
* \class AbstractDBusServiceInterface
* \ingroup servicesideimpl
* \headerfile TelepathyQt/dbus-service.h <TelepathyQt/AbstractDBusServiceInterface>
*
* \brief Base class for D-Bus service interfaces.
*
* This class serves as a base for all the classes that are used to implement
* interfaces that sit on top of D-Bus services.
*/
/**
* Construct an AbstractDBusServiceInterface that implements
* the interface with the given \a interfaceName.
*
* \param interfaceName The name of the interface that this class implements.
*/
AbstractDBusServiceInterface::AbstractDBusServiceInterface(const QString &interfaceName)
: mPriv(new Private(interfaceName))
{
}
/**
* Class destructor.
*/
AbstractDBusServiceInterface::~AbstractDBusServiceInterface()
{
delete mPriv;
}
/**
* Return the name of the interface that this class implements,
* as given on the constructor.
*
* \return The name of the interface that this class implements.
*/
QString AbstractDBusServiceInterface::interfaceName() const
{
return mPriv->interfaceName;
}
/**
* Return the DBusObject on which the adaptor of this interface is plugged.
*
* This is only accessible after the interface has been registered
* with registerInterface().
*
* \return a pointer to the DBusObject on which the adaptor
* of this interface is plugged.
* \sa DBusService::dbusObject()
*/
DBusObject *AbstractDBusServiceInterface::dbusObject() const
{
return mPriv->dbusObject;
}
/**
* Return whether this interface has been registered.
*
* \return \c true if the service has been registered, or \c false otherwise.
* \sa registerInterface()
*/
bool AbstractDBusServiceInterface::isRegistered() const
{
return mPriv->registered;
}
/**
* Registers this interface by plugging its adaptor
* on the given \a dbusObject.
*
* \param dbusObject The object on which to plug the adaptor.
* \return \c false if the interface has already been registered,
* or \a true otherwise.
* \sa isRegistered()
*/
bool AbstractDBusServiceInterface::registerInterface(DBusObject *dbusObject)
{
if (mPriv->registered) {
return true;
}
mPriv->dbusObject = dbusObject;
createAdaptor();
mPriv->registered = true;
return true;
}
/**
* \fn QVariantMap AbstractDBusServiceInterface::immutableProperties() const
*
* Return the immutable properties of this interface.
*
* Immutable properties cannot change after the interface has been registered
* on a service on the bus with registerInterface().
*
* \return The immutable properties of this interface.
*/
/**
* \fn void AbstractDBusServiceInterface::createAdaptor()
*
* Create the adaptor for this interface.
*
* Subclasses should reimplement this appropriately.
*/
}
<|endoftext|> |
<commit_before>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2010 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/AccountSet>
#include "TelepathyQt4/account-set-internal.h"
#include "TelepathyQt4/_gen/account-set.moc.hpp"
#include "TelepathyQt4/_gen/account-set-internal.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/Account>
#include <TelepathyQt4/AccountManager>
#include <TelepathyQt4/ConnectionCapabilities>
#include <TelepathyQt4/ConnectionManager>
namespace Tp
{
AccountSet::Private::Private(AccountSet *parent,
const AccountManagerPtr &accountManager,
const QList<AccountFilterConstPtr> &filters)
: parent(parent),
accountManager(accountManager),
filters(filters),
ready(false)
{
init();
}
AccountSet::Private::Private(AccountSet *parent,
const AccountManagerPtr &accountManager,
const QVariantMap &filter)
: parent(parent),
accountManager(accountManager),
ready(false)
{
AccountPropertyFilterPtr filterObj = AccountPropertyFilter::create();
for (QVariantMap::const_iterator i = filter.constBegin();
i != filter.constEnd(); ++i) {
filterObj->addProperty(i.key(), i.value());
}
filters.append(filterObj);
init();
}
void AccountSet::Private::init()
{
if (checkFilters()) {
connectSignals();
insertAccounts();
ready = true;
}
}
bool AccountSet::Private::checkFilters()
{
foreach (const AccountFilterConstPtr &filter, filters) {
if (!filter->isValid()) {
return false;
}
}
return true;
}
void AccountSet::Private::connectSignals()
{
parent->connect(accountManager.data(),
SIGNAL(newAccount(Tp::AccountPtr)),
SLOT(onNewAccount(Tp::AccountPtr)));
}
void AccountSet::Private::insertAccounts()
{
foreach (const Tp::AccountPtr &account, accountManager->allAccounts()) {
insertAccount(account);
}
}
void AccountSet::Private::insertAccount(const Tp::AccountPtr &account)
{
QString accountPath = account->objectPath();
Q_ASSERT(!wrappers.contains(accountPath));
wrapAccount(account);
filterAccount(account);
}
void AccountSet::Private::removeAccount(const Tp::AccountPtr &account)
{
QString accountPath = account->objectPath();
Q_ASSERT(wrappers.contains(accountPath));
accounts.remove(accountPath);
AccountWrapper *wrapper = wrappers[accountPath];
delete wrapper;
emit parent->accountRemoved(account);
}
void AccountSet::Private::wrapAccount(const AccountPtr &account)
{
AccountWrapper *wrapper = new AccountWrapper(account, parent);
parent->connect(wrapper,
SIGNAL(accountRemoved(Tp::AccountPtr)),
SLOT(onAccountRemoved(Tp::AccountPtr)));
parent->connect(wrapper,
SIGNAL(accountPropertyChanged(Tp::AccountPtr,QString)),
SLOT(onAccountChanged(Tp::AccountPtr)));
parent->connect(wrapper,
SIGNAL(accountCapabilitiesChanged(Tp::AccountPtr,Tp::ConnectionCapabilities*)),
SLOT(onAccountChanged(Tp::AccountPtr)));
wrappers.insert(account->objectPath(), wrapper);
}
void AccountSet::Private::filterAccount(const AccountPtr &account)
{
QString accountPath = account->objectPath();
Q_ASSERT(wrappers.contains(accountPath));
AccountWrapper *wrapper = wrappers[accountPath];
/* account changed, let's check if it matches filter */
if (accountMatchFilters(wrapper)) {
if (!accounts.contains(account->objectPath())) {
accounts.insert(account->objectPath(), account);
if (ready) {
emit parent->accountAdded(account);
}
}
} else {
if (accounts.contains(account->objectPath())) {
accounts.remove(account->objectPath());
if (ready) {
emit parent->accountRemoved(account);
}
}
}
}
bool AccountSet::Private::accountMatchFilters(AccountWrapper *wrapper)
{
if (filters.isEmpty()) {
return true;
}
AccountPtr account = wrapper->account();
foreach (const AccountFilterConstPtr &filter, filters) {
if (!filter->matches(account)) {
return false;
}
}
return true;
}
AccountSet::Private::AccountWrapper::AccountWrapper(
const AccountPtr &account, QObject *parent)
: QObject(parent),
mAccount(account)
{
connect(account.data(),
SIGNAL(removed()),
SLOT(onAccountRemoved()));
connect(account.data(),
SIGNAL(propertyChanged(QString)),
SLOT(onAccountPropertyChanged(QString)));
connect(account.data(),
SIGNAL(capabilitiesChanged(Tp::ConnectionCapabilities*)),
SLOT(onAccountCapalitiesChanged(Tp::ConnectionCapabilities*)));
}
AccountSet::Private::AccountWrapper::~AccountWrapper()
{
}
ConnectionCapabilities *AccountSet::Private::AccountWrapper::capabilities() const
{
if (mAccount->haveConnection() &&
mAccount->connection()->status() == Connection::StatusConnected) {
return mAccount->connection()->capabilities();
} else {
if (mAccount->protocolInfo()) {
return mAccount->protocolInfo()->capabilities();
}
}
/* either we don't have a connected connection or
* Account::FeatureProtocolInfo is not ready */
return 0;
}
void AccountSet::Private::AccountWrapper::onAccountRemoved()
{
emit accountRemoved(mAccount);
}
void AccountSet::Private::AccountWrapper::onAccountPropertyChanged(
const QString &propertyName)
{
emit accountPropertyChanged(mAccount, propertyName);
}
void AccountSet::Private::AccountWrapper::onAccountCapalitiesChanged(
ConnectionCapabilities *caps)
{
emit accountCapabilitiesChanged(mAccount, caps);
}
/**
* \class AccountSet
* \ingroup clientaccount
* \headerfile TelepathyQt4/account-set.h <TelepathyQt4/AccountSet>
*
* \brief The AccountSet class provides an object representing a set of
* Telepathy accounts filtered by a given criteria.
*
* AccountSet is automatically updated whenever accounts that match the given
* criteria are added, removed or updated.
*
* \section account_set_usage_sec Usage
*
* \subsection account_set_create_sec Creating an AccountSet object
*
* The easiest way to create AccountSet objects is through AccountManager. One
* can just use the AccountManager convenience methods such as
* AccountManager::validAccountsSet() to get a set of account objects
* representing valid accounts.
*
* For example:
*
* \code
*
* class MyClass : public QObject
* {
* QOBJECT
*
* public:
* MyClass(QObject *parent = 0);
* ~MyClass() { }
*
* private Q_SLOTS:
* void onAccountManagerReady(Tp::PendingOperation *);
* void onValidAccountAdded(const Tp::AccountPtr &);
* void onValidAccountRemoved(const Tp::AccountPtr &);
*
* private:
* AccountManagerPtr am;
* AccountSetPtr validAccountsSet;
* };
*
* MyClass::MyClass(QObject *parent)
* : QObject(parent)
* am(AccountManager::create())
* {
* connect(am->becomeReady(),
* SIGNAL(finished(Tp::PendingOperation*)),
* SLOT(onAccountManagerReady(Tp::PendingOperation*)));
* }
*
* void MyClass::onAccountManagerReady(Tp::PendingOperation *op)
* {
* if (op->isError()) {
* qWarning() << "Account manager cannot become ready:" <<
* op->errorName() << "-" << op->errorMessage();
* return;
* }
*
* validAccountsSet = am->validAccountsSet();
* connect(validAccountsSet.data(),
* SIGNAL(accountAdded(const Tp::AccountPtr &)),
* SLOT(onValidAccountAdded(const Tp::AccountPtr &)));
* connect(validAccountsSet.data(),
* SIGNAL(accountRemoved(const Tp::AccountPtr &)),
* SLOT(onValidAccountRemoved(const Tp::AccountPtr &)));
*
* QList<AccountPtr> accounts = validAccountsSet->accounts();
* // do something with accounts
* }
*
* void MyClass::onValidAccountAdded(const Tp::AccountPtr &account)
* {
* // do something with account
* }
*
* void MyClass::onValidAccountRemoved(const Tp::AccountPtr &account)
* {
* // do something with account
* }
*
* \endcode
*
* You can also define your own filter using AccountManager::filterAccounts:
*
* \code
*
* void MyClass::onAccountManagerReady(Tp::PendingOperation *op)
* {
* ...
*
* QList<AccountFilterConstPtr> filters;
* AccountPropertyFilterPtr filter = AccountPropertyFilter::create();
* filter->addProperty(QLatin1String("protocolName"), QLatin1String("jabber"));
* filter->addProperty(QLatin1String("enabled"), true);
* filters.append(filter);
*
* AccountSetPtr filteredAccountSet = am->filterAccounts(filter);
* // connect to AccountSet::accountAdded/accountRemoved signals
* QList<AccountPtr> accounts = filteredAccountSet->accounts();
* // do something with accounts
*
* ....
* }
*
* \endcode
*
* Note that for AccountSet to property work with AccountCapabilityFilter
* objects, the feature Account::FeatureCapabilities need to be enabled in all
* accounts return by the AccountManager passed as param in the constructor.
* The easiest way to do this is to enable AccountManager feature
* AccountManager::FeatureFilterByCapabilities.
*
* AccountSet can also be instantiated directly, but when doing it,
* the AccountManager object passed as param in the constructor must be ready
* for AccountSet properly work.
*/
/**
* Construct a new AccountSet object.
*
* \param accountManager An account manager object used to filter accounts.
* The account manager object must be ready.
* \param filters The desired filter.
*/
AccountSet::AccountSet(const AccountManagerPtr &accountManager,
const QList<AccountFilterConstPtr> &filters)
: QObject(),
mPriv(new Private(this, accountManager, filters))
{
}
/**
* Construct a new AccountSet object.
*
* The \a filter must contain Account property names and values as map items.
*
* \param accountManager An account manager object used to filter accounts.
* The account manager object must be ready.
* \param filter The desired filter.
*/
AccountSet::AccountSet(const AccountManagerPtr &accountManager,
const QVariantMap &filter)
: QObject(),
mPriv(new Private(this, accountManager, filter))
{
}
/**
* Class destructor.
*/
AccountSet::~AccountSet()
{
}
/**
* Return the account manager object used to filter accounts.
*
* \return The AccountManager object used to filter accounts.
*/
AccountManagerPtr AccountSet::accountManager() const
{
return mPriv->accountManager;
}
/**
* Return whether the filter returned by filter()/filters() is valid.
*
* If the filter is invalid accounts() will always return an empty list.
*
* This method is deprecated and should not be used in newly written code. Use
* Filter::isValid() instead.
*
* \return \c true if the filter returned by filter()/filters() is valid, otherwise \c
* false.
*/
bool AccountSet::isFilterValid() const
{
foreach (const AccountFilterConstPtr &filter, filters()) {
if (!filter->isValid()) {
return false;
}
}
return true;
}
/**
* Return the filter used to filter accounts.
*
* The filter is composed by Account property names and values as map items.
*
* This method is deprecated and should not be used in newly written code. Use
* filters() instead.
*
* \return A QVariantMap representing the filter used to filter accounts.
*/
QVariantMap AccountSet::filter() const
{
QVariantMap result;
foreach (const AccountFilterConstPtr &filter, mPriv->filters) {
const AccountPropertyFilterConstPtr filterObj =
AccountPropertyFilterConstPtr::dynamicCast(filter);
if (filterObj) {
result.unite(filterObj->filter());
}
}
return result;
}
/**
* Return the filters used to filter accounts.
*
* \return A list of filter objects used to filter accounts.
*/
QList<AccountFilterConstPtr> AccountSet::filters() const
{
return mPriv->filters;
}
/**
* Return a list of account objects that match filters().
*
* \return A list of account objects that match filters().
*/
QList<AccountPtr> AccountSet::accounts() const
{
return mPriv->accounts.values();
}
/**
* \fn void AccountSet::accountAdded(const Tp::AccountPtr &account);
*
* This signal is emitted whenever an account that matches filters() is added to
* this set.
*
* \param account The account that was added to this set.
*/
/**
* \fn void AccountSet::accountRemoved(const Tp::AccountPtr &account);
*
* This signal is emitted whenever an account that matches filters() is removed
* from this set.
*
* \param account The account that was removed from this set.
*/
void AccountSet::onNewAccount(const AccountPtr &account)
{
mPriv->insertAccount(account);
}
void AccountSet::onAccountRemoved(const AccountPtr &account)
{
mPriv->removeAccount(account);
}
void AccountSet::onAccountChanged(const AccountPtr &account)
{
mPriv->filterAccount(account);
}
} // Tp
<commit_msg>AccountSet: Don't leave wrappers around when accounts are removed<commit_after>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2010 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/AccountSet>
#include "TelepathyQt4/account-set-internal.h"
#include "TelepathyQt4/_gen/account-set.moc.hpp"
#include "TelepathyQt4/_gen/account-set-internal.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/Account>
#include <TelepathyQt4/AccountManager>
#include <TelepathyQt4/ConnectionCapabilities>
#include <TelepathyQt4/ConnectionManager>
namespace Tp
{
AccountSet::Private::Private(AccountSet *parent,
const AccountManagerPtr &accountManager,
const QList<AccountFilterConstPtr> &filters)
: parent(parent),
accountManager(accountManager),
filters(filters),
ready(false)
{
init();
}
AccountSet::Private::Private(AccountSet *parent,
const AccountManagerPtr &accountManager,
const QVariantMap &filter)
: parent(parent),
accountManager(accountManager),
ready(false)
{
AccountPropertyFilterPtr filterObj = AccountPropertyFilter::create();
for (QVariantMap::const_iterator i = filter.constBegin();
i != filter.constEnd(); ++i) {
filterObj->addProperty(i.key(), i.value());
}
filters.append(filterObj);
init();
}
void AccountSet::Private::init()
{
if (checkFilters()) {
connectSignals();
insertAccounts();
ready = true;
}
}
bool AccountSet::Private::checkFilters()
{
foreach (const AccountFilterConstPtr &filter, filters) {
if (!filter->isValid()) {
return false;
}
}
return true;
}
void AccountSet::Private::connectSignals()
{
parent->connect(accountManager.data(),
SIGNAL(newAccount(Tp::AccountPtr)),
SLOT(onNewAccount(Tp::AccountPtr)));
}
void AccountSet::Private::insertAccounts()
{
foreach (const Tp::AccountPtr &account, accountManager->allAccounts()) {
insertAccount(account);
}
}
void AccountSet::Private::insertAccount(const Tp::AccountPtr &account)
{
QString accountPath = account->objectPath();
Q_ASSERT(!wrappers.contains(accountPath));
wrapAccount(account);
filterAccount(account);
}
void AccountSet::Private::removeAccount(const Tp::AccountPtr &account)
{
QString accountPath = account->objectPath();
Q_ASSERT(wrappers.contains(accountPath));
accounts.remove(accountPath);
AccountWrapper *wrapper = wrappers.take(accountPath);
wrapper->deleteLater();
emit parent->accountRemoved(account);
}
void AccountSet::Private::wrapAccount(const AccountPtr &account)
{
AccountWrapper *wrapper = new AccountWrapper(account, parent);
parent->connect(wrapper,
SIGNAL(accountRemoved(Tp::AccountPtr)),
SLOT(onAccountRemoved(Tp::AccountPtr)));
parent->connect(wrapper,
SIGNAL(accountPropertyChanged(Tp::AccountPtr,QString)),
SLOT(onAccountChanged(Tp::AccountPtr)));
parent->connect(wrapper,
SIGNAL(accountCapabilitiesChanged(Tp::AccountPtr,Tp::ConnectionCapabilities*)),
SLOT(onAccountChanged(Tp::AccountPtr)));
wrappers.insert(account->objectPath(), wrapper);
}
void AccountSet::Private::filterAccount(const AccountPtr &account)
{
QString accountPath = account->objectPath();
Q_ASSERT(wrappers.contains(accountPath));
AccountWrapper *wrapper = wrappers[accountPath];
/* account changed, let's check if it matches filter */
if (accountMatchFilters(wrapper)) {
if (!accounts.contains(account->objectPath())) {
accounts.insert(account->objectPath(), account);
if (ready) {
emit parent->accountAdded(account);
}
}
} else {
if (accounts.contains(account->objectPath())) {
accounts.remove(account->objectPath());
if (ready) {
emit parent->accountRemoved(account);
}
}
}
}
bool AccountSet::Private::accountMatchFilters(AccountWrapper *wrapper)
{
if (filters.isEmpty()) {
return true;
}
AccountPtr account = wrapper->account();
foreach (const AccountFilterConstPtr &filter, filters) {
if (!filter->matches(account)) {
return false;
}
}
return true;
}
AccountSet::Private::AccountWrapper::AccountWrapper(
const AccountPtr &account, QObject *parent)
: QObject(parent),
mAccount(account)
{
connect(account.data(),
SIGNAL(removed()),
SLOT(onAccountRemoved()));
connect(account.data(),
SIGNAL(propertyChanged(QString)),
SLOT(onAccountPropertyChanged(QString)));
connect(account.data(),
SIGNAL(capabilitiesChanged(Tp::ConnectionCapabilities*)),
SLOT(onAccountCapalitiesChanged(Tp::ConnectionCapabilities*)));
}
AccountSet::Private::AccountWrapper::~AccountWrapper()
{
}
ConnectionCapabilities *AccountSet::Private::AccountWrapper::capabilities() const
{
if (mAccount->haveConnection() &&
mAccount->connection()->status() == Connection::StatusConnected) {
return mAccount->connection()->capabilities();
} else {
if (mAccount->protocolInfo()) {
return mAccount->protocolInfo()->capabilities();
}
}
/* either we don't have a connected connection or
* Account::FeatureProtocolInfo is not ready */
return 0;
}
void AccountSet::Private::AccountWrapper::onAccountRemoved()
{
emit accountRemoved(mAccount);
}
void AccountSet::Private::AccountWrapper::onAccountPropertyChanged(
const QString &propertyName)
{
emit accountPropertyChanged(mAccount, propertyName);
}
void AccountSet::Private::AccountWrapper::onAccountCapalitiesChanged(
ConnectionCapabilities *caps)
{
emit accountCapabilitiesChanged(mAccount, caps);
}
/**
* \class AccountSet
* \ingroup clientaccount
* \headerfile TelepathyQt4/account-set.h <TelepathyQt4/AccountSet>
*
* \brief The AccountSet class provides an object representing a set of
* Telepathy accounts filtered by a given criteria.
*
* AccountSet is automatically updated whenever accounts that match the given
* criteria are added, removed or updated.
*
* \section account_set_usage_sec Usage
*
* \subsection account_set_create_sec Creating an AccountSet object
*
* The easiest way to create AccountSet objects is through AccountManager. One
* can just use the AccountManager convenience methods such as
* AccountManager::validAccountsSet() to get a set of account objects
* representing valid accounts.
*
* For example:
*
* \code
*
* class MyClass : public QObject
* {
* QOBJECT
*
* public:
* MyClass(QObject *parent = 0);
* ~MyClass() { }
*
* private Q_SLOTS:
* void onAccountManagerReady(Tp::PendingOperation *);
* void onValidAccountAdded(const Tp::AccountPtr &);
* void onValidAccountRemoved(const Tp::AccountPtr &);
*
* private:
* AccountManagerPtr am;
* AccountSetPtr validAccountsSet;
* };
*
* MyClass::MyClass(QObject *parent)
* : QObject(parent)
* am(AccountManager::create())
* {
* connect(am->becomeReady(),
* SIGNAL(finished(Tp::PendingOperation*)),
* SLOT(onAccountManagerReady(Tp::PendingOperation*)));
* }
*
* void MyClass::onAccountManagerReady(Tp::PendingOperation *op)
* {
* if (op->isError()) {
* qWarning() << "Account manager cannot become ready:" <<
* op->errorName() << "-" << op->errorMessage();
* return;
* }
*
* validAccountsSet = am->validAccountsSet();
* connect(validAccountsSet.data(),
* SIGNAL(accountAdded(const Tp::AccountPtr &)),
* SLOT(onValidAccountAdded(const Tp::AccountPtr &)));
* connect(validAccountsSet.data(),
* SIGNAL(accountRemoved(const Tp::AccountPtr &)),
* SLOT(onValidAccountRemoved(const Tp::AccountPtr &)));
*
* QList<AccountPtr> accounts = validAccountsSet->accounts();
* // do something with accounts
* }
*
* void MyClass::onValidAccountAdded(const Tp::AccountPtr &account)
* {
* // do something with account
* }
*
* void MyClass::onValidAccountRemoved(const Tp::AccountPtr &account)
* {
* // do something with account
* }
*
* \endcode
*
* You can also define your own filter using AccountManager::filterAccounts:
*
* \code
*
* void MyClass::onAccountManagerReady(Tp::PendingOperation *op)
* {
* ...
*
* QList<AccountFilterConstPtr> filters;
* AccountPropertyFilterPtr filter = AccountPropertyFilter::create();
* filter->addProperty(QLatin1String("protocolName"), QLatin1String("jabber"));
* filter->addProperty(QLatin1String("enabled"), true);
* filters.append(filter);
*
* AccountSetPtr filteredAccountSet = am->filterAccounts(filter);
* // connect to AccountSet::accountAdded/accountRemoved signals
* QList<AccountPtr> accounts = filteredAccountSet->accounts();
* // do something with accounts
*
* ....
* }
*
* \endcode
*
* Note that for AccountSet to property work with AccountCapabilityFilter
* objects, the feature Account::FeatureCapabilities need to be enabled in all
* accounts return by the AccountManager passed as param in the constructor.
* The easiest way to do this is to enable AccountManager feature
* AccountManager::FeatureFilterByCapabilities.
*
* AccountSet can also be instantiated directly, but when doing it,
* the AccountManager object passed as param in the constructor must be ready
* for AccountSet properly work.
*/
/**
* Construct a new AccountSet object.
*
* \param accountManager An account manager object used to filter accounts.
* The account manager object must be ready.
* \param filters The desired filter.
*/
AccountSet::AccountSet(const AccountManagerPtr &accountManager,
const QList<AccountFilterConstPtr> &filters)
: QObject(),
mPriv(new Private(this, accountManager, filters))
{
}
/**
* Construct a new AccountSet object.
*
* The \a filter must contain Account property names and values as map items.
*
* \param accountManager An account manager object used to filter accounts.
* The account manager object must be ready.
* \param filter The desired filter.
*/
AccountSet::AccountSet(const AccountManagerPtr &accountManager,
const QVariantMap &filter)
: QObject(),
mPriv(new Private(this, accountManager, filter))
{
}
/**
* Class destructor.
*/
AccountSet::~AccountSet()
{
}
/**
* Return the account manager object used to filter accounts.
*
* \return The AccountManager object used to filter accounts.
*/
AccountManagerPtr AccountSet::accountManager() const
{
return mPriv->accountManager;
}
/**
* Return whether the filter returned by filter()/filters() is valid.
*
* If the filter is invalid accounts() will always return an empty list.
*
* This method is deprecated and should not be used in newly written code. Use
* Filter::isValid() instead.
*
* \return \c true if the filter returned by filter()/filters() is valid, otherwise \c
* false.
*/
bool AccountSet::isFilterValid() const
{
foreach (const AccountFilterConstPtr &filter, filters()) {
if (!filter->isValid()) {
return false;
}
}
return true;
}
/**
* Return the filter used to filter accounts.
*
* The filter is composed by Account property names and values as map items.
*
* This method is deprecated and should not be used in newly written code. Use
* filters() instead.
*
* \return A QVariantMap representing the filter used to filter accounts.
*/
QVariantMap AccountSet::filter() const
{
QVariantMap result;
foreach (const AccountFilterConstPtr &filter, mPriv->filters) {
const AccountPropertyFilterConstPtr filterObj =
AccountPropertyFilterConstPtr::dynamicCast(filter);
if (filterObj) {
result.unite(filterObj->filter());
}
}
return result;
}
/**
* Return the filters used to filter accounts.
*
* \return A list of filter objects used to filter accounts.
*/
QList<AccountFilterConstPtr> AccountSet::filters() const
{
return mPriv->filters;
}
/**
* Return a list of account objects that match filters().
*
* \return A list of account objects that match filters().
*/
QList<AccountPtr> AccountSet::accounts() const
{
return mPriv->accounts.values();
}
/**
* \fn void AccountSet::accountAdded(const Tp::AccountPtr &account);
*
* This signal is emitted whenever an account that matches filters() is added to
* this set.
*
* \param account The account that was added to this set.
*/
/**
* \fn void AccountSet::accountRemoved(const Tp::AccountPtr &account);
*
* This signal is emitted whenever an account that matches filters() is removed
* from this set.
*
* \param account The account that was removed from this set.
*/
void AccountSet::onNewAccount(const AccountPtr &account)
{
mPriv->insertAccount(account);
}
void AccountSet::onAccountRemoved(const AccountPtr &account)
{
mPriv->removeAccount(account);
}
void AccountSet::onAccountChanged(const AccountPtr &account)
{
mPriv->filterAccount(account);
}
} // Tp
<|endoftext|> |
<commit_before>/* Copyright (C) 2008-2011 Xavier Pujol
(C) 2015 Michael Walter.
(C) 2016 Marc Stevens. (generic improvements, auxiliary solutions, subsolutions)
(C) 2016 Guillaume Bonnoron. (CVP improvements)
This file is part of fplll. fplll 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.
fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */
#include "enumerate_base.h"
FPLLL_BEGIN_NAMESPACE
#ifdef FPLLL_WITH_RECURSIVE_ENUM
template <int kk, int kk_start, bool dualenum, bool findsubsols, bool enable_reset>
inline void EnumerationBase::enumerate_recursive(
EnumerationBase::opts<kk, kk_start, dualenum, findsubsols, enable_reset>)
{
enumf alphak = x[kk] - center[kk];
enumf newdist = partdist[kk] + alphak * alphak * rdiag[kk];
if (!(newdist <= partdistbounds[kk]))
return;
++nodes[kk];
alpha[kk] = alphak;
if (findsubsols && newdist < subsoldists[kk] && newdist != 0.0)
{
subsoldists[kk] = newdist;
process_subsolution(kk, newdist);
}
if (kk == 0)
{
if (newdist > 0.0 || !is_svp)
process_solution(newdist);
}
else if (enable_reset &&
kk < reset_depth) // in CVP, below the max GS vector, we reset the partial distance
{
reset(newdist, kk);
return;
}
else
{
partdist[kk - 1] = newdist;
if (dualenum)
{
for (int j = center_partsum_begin[kk]; j > kk - 1; --j)
center_partsums[kk - 1][j] = center_partsums[kk - 1][j + 1] - alpha[j] * mut[kk - 1][j];
}
else
{
for (int j = center_partsum_begin[kk]; j > kk - 1; --j)
center_partsums[kk - 1][j] = center_partsums[kk - 1][j + 1] - x[j] * mut[kk - 1][j];
}
if (center_partsum_begin[kk] > center_partsum_begin[kk - 1])
center_partsum_begin[kk - 1] = center_partsum_begin[kk];
center_partsum_begin[kk] = kk;
center[kk - 1] = center_partsums[kk - 1][kk];
roundto(x[kk - 1], center[kk - 1]);
dx[kk - 1] = ddx[kk - 1] = (((int)(center[kk - 1] >= x[kk - 1]) & 1) << 1) - 1;
}
while (true)
{
FPLLL_TRACE("Level k=" << kk << " dist_k=" << partdist[kk] << " x_k=" << x[kk]
<< " newdist=" << newdist << " partdistbounds_k=" << partdistbounds[kk]);
enumerate_recursive(opts<kk - 1, kk_start, dualenum, findsubsols, enable_reset>());
if (partdist[kk] != 0.0)
{
x[kk] += dx[kk];
ddx[kk] = -ddx[kk];
dx[kk] = ddx[kk] - dx[kk];
enumf alphak2 = x[kk] - center[kk];
enumf newdist2 = partdist[kk] + alphak2 * alphak2 * rdiag[kk];
if (!(newdist2 <= partdistbounds[kk]))
return;
++nodes[kk];
alpha[kk] = alphak2;
if (kk == 0)
{
if (newdist2 > 0.0 || !is_svp)
process_solution(newdist2);
}
else
{
partdist[kk - 1] = newdist2;
if (dualenum)
center_partsums[kk - 1][kk - 1 + 1] =
center_partsums[kk - 1][kk - 1 + 1 + 1] - alpha[kk - 1 + 1] * mut[kk - 1][kk - 1 + 1];
else
center_partsums[kk - 1][kk - 1 + 1] =
center_partsums[kk - 1][kk - 1 + 1 + 1] - x[kk - 1 + 1] * mut[kk - 1][kk - 1 + 1];
if (kk > center_partsum_begin[kk - 1])
center_partsum_begin[kk - 1] = kk;
center[kk - 1] = center_partsums[kk - 1][kk - 1 + 1];
roundto(x[kk - 1], center[kk - 1]);
dx[kk - 1] = ddx[kk - 1] = (((int)(center[kk - 1] >= x[kk - 1]) & 1) << 1) - 1;
}
}
else
{
++x[kk];
enumf alphak2 = x[kk] - center[kk];
enumf newdist2 = partdist[kk] + alphak2 * alphak2 * rdiag[kk];
if (!(newdist2 <= partdistbounds[kk]))
return;
++nodes[kk];
alpha[kk] = alphak2;
if (kk == 0)
{
if (newdist2 > 0.0 || !is_svp)
process_solution(newdist2);
}
else
{
partdist[kk - 1] = newdist2;
if (dualenum)
center_partsums[kk - 1][kk - 1 + 1] =
center_partsums[kk - 1][kk - 1 + 1 + 1] - alpha[kk - 1 + 1] * mut[kk - 1][kk - 1 + 1];
else
center_partsums[kk - 1][kk - 1 + 1] =
center_partsums[kk - 1][kk - 1 + 1 + 1] - x[kk - 1 + 1] * mut[kk - 1][kk - 1 + 1];
if (kk > center_partsum_begin[kk - 1])
center_partsum_begin[kk - 1] = kk;
center[kk - 1] = center_partsums[kk - 1][kk - 1 + 1];
roundto(x[kk - 1], center[kk - 1]);
dx[kk - 1] = ddx[kk - 1] = (((int)(center[kk - 1] >= x[kk - 1]) & 1) << 1) - 1;
}
}
}
}
#define ENUM_TABLE_FILL8(a) \
&EnumerationBase::enumerate_recursive_wrapper<a + 0, dualenum, findsubsols, enable_reset>, \
&EnumerationBase::enumerate_recursive_wrapper<a + 1, dualenum, findsubsols, enable_reset>, \
&EnumerationBase::enumerate_recursive_wrapper<a + 2, dualenum, findsubsols, enable_reset>, \
&EnumerationBase::enumerate_recursive_wrapper<a + 3, dualenum, findsubsols, enable_reset>, \
&EnumerationBase::enumerate_recursive_wrapper<a + 4, dualenum, findsubsols, enable_reset>, \
&EnumerationBase::enumerate_recursive_wrapper<a + 5, dualenum, findsubsols, enable_reset>, \
&EnumerationBase::enumerate_recursive_wrapper<a + 6, dualenum, findsubsols, enable_reset>, \
&EnumerationBase::enumerate_recursive_wrapper<a + 7, dualenum, findsubsols, enable_reset>
#define ENUM_TABLE_FILL64(a) \
ENUM_TABLE_FILL8(a) \
, ENUM_TABLE_FILL8(a + 8), ENUM_TABLE_FILL8(a + 16), ENUM_TABLE_FILL8(a + 24), \
ENUM_TABLE_FILL8(a + 32), ENUM_TABLE_FILL8(a + 40), ENUM_TABLE_FILL8(a + 48), \
ENUM_TABLE_FILL8(a + 56)
#define ENUM_TABLE_FILL256(a) \
ENUM_TABLE_FILL64(a) \
, ENUM_TABLE_FILL64(a + 64), ENUM_TABLE_FILL64(a + 128), ENUM_TABLE_FILL64(a + 192)
template <bool dualenum, bool findsubsols, bool enable_reset>
inline void EnumerationBase::enumerate_recursive_dispatch(int kk)
{
typedef void (EnumerationBase::*enum_recur_type)();
static const enum_recur_type lookup[] = {
ENUM_TABLE_FILL256(0), ENUM_TABLE_FILL256(256), ENUM_TABLE_FILL256(512),
ENUM_TABLE_FILL256(768), ENUM_TABLE_FILL256(1024), ENUM_TABLE_FILL256(1280),
ENUM_TABLE_FILL256(1536), ENUM_TABLE_FILL256(1792),
};
(this->*lookup[kk])();
}
#endif
template <bool dualenum, bool findsubsols, bool enable_reset> void EnumerationBase::enumerate_loop()
{
if (k >= k_end)
return;
center_partsum_begin[0] = 0;
for (int i = 0; i < k_end; ++i)
{
center_partsum_begin[i + 1] = k_end - 1;
center_partsums[i][k_end] = center_partsum[i];
}
partdist[k_end] = 0.0; // needed to make next_pos_up() work properly
nodes[k_end] -= k_end - k;
k = k_end - 1;
#ifdef FPLLL_WITH_RECURSIVE_ENUM
enumerate_recursive_dispatch<dualenum, findsubsols, enable_reset>(k);
return;
#endif
finished = false;
while (!finished)
{
enumf alphak = x[k] - center[k];
enumf newdist = partdist[k] + alphak * alphak * rdiag[k];
FPLLL_TRACE("Level k=" << k << " dist_k=" << partdist[k] << " x_k=" << x[k]
<< " newdist=" << newdist << " partdistbounds_k=" << partdistbounds[k]);
if (newdist <= partdistbounds[k])
{
++nodes[k];
alpha[k] = alphak;
if (findsubsols && newdist < subsoldists[k] && newdist != 0.0)
{
subsoldists[k] = newdist;
process_subsolution(k, newdist);
}
--k;
if (k < 0)
{
if (newdist > 0.0 || !is_svp)
process_solution(newdist);
finished = !next_pos_up();
continue;
}
if (enable_reset &&
k < reset_depth) // in CVP, below the max GS vector, we reset the partial distance
{
reset(newdist, k);
finished = !next_pos_up();
continue;
}
if (dualenum)
{
for (int j = center_partsum_begin[k + 1]; j > k; --j)
center_partsums[k][j] = center_partsums[k][j + 1] - alpha[j] * mut[k][j];
}
else
{
for (int j = center_partsum_begin[k + 1]; j > k; --j)
center_partsums[k][j] = center_partsums[k][j + 1] - x[j] * mut[k][j];
}
center_partsum_begin[k] = max(center_partsum_begin[k], center_partsum_begin[k + 1]);
center_partsum_begin[k + 1] = k + 1;
enumf newcenter = center_partsums[k][k + 1];
center[k] = newcenter;
partdist[k] = newdist;
roundto(x[k], newcenter);
dx[k] = ddx[k] = (((int)(newcenter >= x[k]) & 1) << 1) - 1;
}
else
{
finished = !next_pos_up();
}
}
}
template void EnumerationBase::enumerate_loop<false, false, true>();
template void EnumerationBase::enumerate_loop<false, true, true>();
template void EnumerationBase::enumerate_loop<false, false, false>();
template void EnumerationBase::enumerate_loop<false, true, false>();
template void EnumerationBase::enumerate_loop<true, false, false>();
template void EnumerationBase::enumerate_loop<true, true, false>();
FPLLL_END_NAMESPACE
<commit_msg>Adjust per level, rather than on k_end<commit_after>/* Copyright (C) 2008-2011 Xavier Pujol
(C) 2015 Michael Walter.
(C) 2016 Marc Stevens. (generic improvements, auxiliary solutions, subsolutions)
(C) 2016 Guillaume Bonnoron. (CVP improvements)
This file is part of fplll. fplll 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.
fplll 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 fplll. If not, see <http://www.gnu.org/licenses/>. */
#include "enumerate_base.h"
FPLLL_BEGIN_NAMESPACE
#ifdef FPLLL_WITH_RECURSIVE_ENUM
template <int kk, int kk_start, bool dualenum, bool findsubsols, bool enable_reset>
inline void EnumerationBase::enumerate_recursive(
EnumerationBase::opts<kk, kk_start, dualenum, findsubsols, enable_reset>)
{
enumf alphak = x[kk] - center[kk];
enumf newdist = partdist[kk] + alphak * alphak * rdiag[kk];
if (!(newdist <= partdistbounds[kk]))
return;
++nodes[kk];
alpha[kk] = alphak;
if (findsubsols && newdist < subsoldists[kk] && newdist != 0.0)
{
subsoldists[kk] = newdist;
process_subsolution(kk, newdist);
}
if (kk == 0)
{
if (newdist > 0.0 || !is_svp)
process_solution(newdist);
}
else if (enable_reset &&
kk < reset_depth) // in CVP, below the max GS vector, we reset the partial distance
{
reset(newdist, kk);
return;
}
else
{
partdist[kk - 1] = newdist;
if (dualenum)
{
for (int j = center_partsum_begin[kk]; j > kk - 1; --j)
center_partsums[kk - 1][j] = center_partsums[kk - 1][j + 1] - alpha[j] * mut[kk - 1][j];
}
else
{
for (int j = center_partsum_begin[kk]; j > kk - 1; --j)
center_partsums[kk - 1][j] = center_partsums[kk - 1][j + 1] - x[j] * mut[kk - 1][j];
}
if (center_partsum_begin[kk] > center_partsum_begin[kk - 1])
center_partsum_begin[kk - 1] = center_partsum_begin[kk];
center_partsum_begin[kk] = kk;
center[kk - 1] = center_partsums[kk - 1][kk];
roundto(x[kk - 1], center[kk - 1]);
dx[kk - 1] = ddx[kk - 1] = (((int)(center[kk - 1] >= x[kk - 1]) & 1) << 1) - 1;
}
while (true)
{
FPLLL_TRACE("Level k=" << kk << " dist_k=" << partdist[kk] << " x_k=" << x[kk]
<< " newdist=" << newdist << " partdistbounds_k=" << partdistbounds[kk]);
enumerate_recursive(opts<kk - 1, kk_start, dualenum, findsubsols, enable_reset>());
if (partdist[kk] != 0.0)
{
x[kk] += dx[kk];
ddx[kk] = -ddx[kk];
dx[kk] = ddx[kk] - dx[kk];
enumf alphak2 = x[kk] - center[kk];
enumf newdist2 = partdist[kk] + alphak2 * alphak2 * rdiag[kk];
if (!(newdist2 <= partdistbounds[kk]))
return;
++nodes[kk];
alpha[kk] = alphak2;
if (kk == 0)
{
if (newdist2 > 0.0 || !is_svp)
process_solution(newdist2);
}
else
{
partdist[kk - 1] = newdist2;
if (dualenum)
center_partsums[kk - 1][kk - 1 + 1] =
center_partsums[kk - 1][kk - 1 + 1 + 1] - alpha[kk - 1 + 1] * mut[kk - 1][kk - 1 + 1];
else
center_partsums[kk - 1][kk - 1 + 1] =
center_partsums[kk - 1][kk - 1 + 1 + 1] - x[kk - 1 + 1] * mut[kk - 1][kk - 1 + 1];
if (kk > center_partsum_begin[kk - 1])
center_partsum_begin[kk - 1] = kk;
center[kk - 1] = center_partsums[kk - 1][kk - 1 + 1];
roundto(x[kk - 1], center[kk - 1]);
dx[kk - 1] = ddx[kk - 1] = (((int)(center[kk - 1] >= x[kk - 1]) & 1) << 1) - 1;
}
}
else
{
++x[kk];
enumf alphak2 = x[kk] - center[kk];
enumf newdist2 = partdist[kk] + alphak2 * alphak2 * rdiag[kk];
if (!(newdist2 <= partdistbounds[kk]))
return;
++nodes[kk];
alpha[kk] = alphak2;
if (kk == 0)
{
if (newdist2 > 0.0 || !is_svp)
process_solution(newdist2);
}
else
{
partdist[kk - 1] = newdist2;
if (dualenum)
center_partsums[kk - 1][kk - 1 + 1] =
center_partsums[kk - 1][kk - 1 + 1 + 1] - alpha[kk - 1 + 1] * mut[kk - 1][kk - 1 + 1];
else
center_partsums[kk - 1][kk - 1 + 1] =
center_partsums[kk - 1][kk - 1 + 1 + 1] - x[kk - 1 + 1] * mut[kk - 1][kk - 1 + 1];
if (kk > center_partsum_begin[kk - 1])
center_partsum_begin[kk - 1] = kk;
center[kk - 1] = center_partsums[kk - 1][kk - 1 + 1];
roundto(x[kk - 1], center[kk - 1]);
dx[kk - 1] = ddx[kk - 1] = (((int)(center[kk - 1] >= x[kk - 1]) & 1) << 1) - 1;
}
}
}
}
#define ENUM_TABLE_FILL8(a) \
&EnumerationBase::enumerate_recursive_wrapper<a + 0, dualenum, findsubsols, enable_reset>, \
&EnumerationBase::enumerate_recursive_wrapper<a + 1, dualenum, findsubsols, enable_reset>, \
&EnumerationBase::enumerate_recursive_wrapper<a + 2, dualenum, findsubsols, enable_reset>, \
&EnumerationBase::enumerate_recursive_wrapper<a + 3, dualenum, findsubsols, enable_reset>, \
&EnumerationBase::enumerate_recursive_wrapper<a + 4, dualenum, findsubsols, enable_reset>, \
&EnumerationBase::enumerate_recursive_wrapper<a + 5, dualenum, findsubsols, enable_reset>, \
&EnumerationBase::enumerate_recursive_wrapper<a + 6, dualenum, findsubsols, enable_reset>, \
&EnumerationBase::enumerate_recursive_wrapper<a + 7, dualenum, findsubsols, enable_reset>
#define ENUM_TABLE_FILL64(a) \
ENUM_TABLE_FILL8(a) \
, ENUM_TABLE_FILL8(a + 8), ENUM_TABLE_FILL8(a + 16), ENUM_TABLE_FILL8(a + 24), \
ENUM_TABLE_FILL8(a + 32), ENUM_TABLE_FILL8(a + 40), ENUM_TABLE_FILL8(a + 48), \
ENUM_TABLE_FILL8(a + 56)
#define ENUM_TABLE_FILL256(a) \
ENUM_TABLE_FILL64(a) \
, ENUM_TABLE_FILL64(a + 64), ENUM_TABLE_FILL64(a + 128), ENUM_TABLE_FILL64(a + 192)
template <bool dualenum, bool findsubsols, bool enable_reset>
inline void EnumerationBase::enumerate_recursive_dispatch(int kk)
{
typedef void (EnumerationBase::*enum_recur_type)();
static const enum_recur_type lookup[] = {
ENUM_TABLE_FILL256(0), ENUM_TABLE_FILL256(256), ENUM_TABLE_FILL256(512),
ENUM_TABLE_FILL256(768), ENUM_TABLE_FILL256(1024), ENUM_TABLE_FILL256(1280),
ENUM_TABLE_FILL256(1536), ENUM_TABLE_FILL256(1792),
};
(this->*lookup[kk])();
}
#endif
template <bool dualenum, bool findsubsols, bool enable_reset> void EnumerationBase::enumerate_loop()
{
if (k >= k_end)
return;
center_partsum_begin[0] = 0;
for (int i = 0; i < k_end; ++i)
{
center_partsum_begin[i + 1] = k_end - 1;
center_partsums[i][k_end] = center_partsum[i];
}
partdist[k_end] = 0.0; // needed to make next_pos_up() work properly
/* The next few lines provide compatibility between the various different enumerators in fplll.
* Because the recursive enumerator needs to start at one level down from the last position, we
* decrement it. However, this has the tendency of screwing up the node count by a factor of k
* (which, although asymptotically shouldn't matter, practically it will). In particular, it has
* the property of meaning we count an extra node per level (in k+1....k_end-1) in the initial
* descent. You can think of this as fplll just Babai lifting from k_end->k. However, clearly this
* may screw up the total - so we adjust this. For more info, see
* https://github.com/fplll/fplll/pull/442.
*
* Note: this adjustment does no checks on the nodes array. This will cause wrap arounds if the
* values are 0. But, adding to these later will reset them, so this should not matter in
* practice.
*/
for (int i = k + 1; i < k_end; i++)
{
nodes[i]--;
}
k = k_end - 1;
#ifdef FPLLL_WITH_RECURSIVE_ENUM
enumerate_recursive_dispatch<dualenum, findsubsols, enable_reset>(k);
return;
#endif
finished = false;
while (!finished)
{
enumf alphak = x[k] - center[k];
enumf newdist = partdist[k] + alphak * alphak * rdiag[k];
FPLLL_TRACE("Level k=" << k << " dist_k=" << partdist[k] << " x_k=" << x[k]
<< " newdist=" << newdist << " partdistbounds_k=" << partdistbounds[k]);
if (newdist <= partdistbounds[k])
{
++nodes[k];
alpha[k] = alphak;
if (findsubsols && newdist < subsoldists[k] && newdist != 0.0)
{
subsoldists[k] = newdist;
process_subsolution(k, newdist);
}
--k;
if (k < 0)
{
if (newdist > 0.0 || !is_svp)
process_solution(newdist);
finished = !next_pos_up();
continue;
}
if (enable_reset &&
k < reset_depth) // in CVP, below the max GS vector, we reset the partial distance
{
reset(newdist, k);
finished = !next_pos_up();
continue;
}
if (dualenum)
{
for (int j = center_partsum_begin[k + 1]; j > k; --j)
center_partsums[k][j] = center_partsums[k][j + 1] - alpha[j] * mut[k][j];
}
else
{
for (int j = center_partsum_begin[k + 1]; j > k; --j)
center_partsums[k][j] = center_partsums[k][j + 1] - x[j] * mut[k][j];
}
center_partsum_begin[k] = max(center_partsum_begin[k], center_partsum_begin[k + 1]);
center_partsum_begin[k + 1] = k + 1;
enumf newcenter = center_partsums[k][k + 1];
center[k] = newcenter;
partdist[k] = newdist;
roundto(x[k], newcenter);
dx[k] = ddx[k] = (((int)(newcenter >= x[k]) & 1) << 1) - 1;
}
else
{
finished = !next_pos_up();
}
}
}
template void EnumerationBase::enumerate_loop<false, false, true>();
template void EnumerationBase::enumerate_loop<false, true, true>();
template void EnumerationBase::enumerate_loop<false, false, false>();
template void EnumerationBase::enumerate_loop<false, true, false>();
template void EnumerationBase::enumerate_loop<true, false, false>();
template void EnumerationBase::enumerate_loop<true, true, false>();
FPLLL_END_NAMESPACE
<|endoftext|> |
<commit_before>// Copyright (c) 2013 The Chromium Embedded Framework 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 "cefsimple/simple_app.h"
#include <string>
#include "cefsimple/simple_handler.h"
#include "include/cef_browser.h"
#include "include/cef_command_line.h"
#include "include/wrapper/cef_helpers.h"
#include <shlwapi.h>
#include <fstream>
HWND SimpleApp::gameWindow = 0;
SimpleApp::SimpleApp() {
}
void GetDesktopResolution(int& horizontal, int& vertical)
{
RECT desktop;
const HWND hDesktop = GetDesktopWindow();
GetWindowRect(hDesktop, &desktop);
horizontal = desktop.right;
vertical = desktop.bottom;
}
void SimpleApp::OnContextInitialized() {
CEF_REQUIRE_UI_THREAD();
// Information used when creating the native window.
CefWindowInfo window_info;
#if defined(OS_WIN)
// On Windows we need to specify certain flags that will be passed to
// CreateWindowEx().
window_info.SetAsPopup(NULL, "Custom Menu");
#endif
int horizontal, vertical;
GetDesktopResolution(horizontal, vertical);
window_info.width = horizontal - 100;
window_info.height = vertical - 100;
int xPos = (horizontal - window_info.width) / 2;
int yPos = (vertical - window_info.height) / 2;
window_info.x = xPos;
window_info.y = yPos;
// SimpleHandler implements browser-level callbacks.
CefRefPtr<SimpleHandler> handler(new SimpleHandler());
// Specify CEF browser settings here.
CefBrowserSettings browser_settings;
wchar_t pathToOurDirectory[260];
GetModuleFileName(NULL, pathToOurDirectory, 260);
PathRemoveFileSpec(pathToOurDirectory);
std::wstring path(pathToOurDirectory);
path.append(L"\\mods\\menus\\default");
CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager(NULL);
manager->SetStoragePath(path, true, NULL);
CefRefPtr<CefCommandLine> command_line = CefCommandLine::GetGlobalCommandLine();
std::wstring url = L"http://thefeeltrain.github.io/";
std::wstring urlString = command_line->GetSwitchValue("url").ToWString();
if (!urlString.empty())
{
url = urlString;
}
std::string hwndString = command_line->GetSwitchValue("hwnd").ToString();
if (!hwndString.empty())
{
gameWindow = (HWND)stoi(hwndString);
ShowWindow(gameWindow, SW_HIDE);
}
else
{
CefShutdown();
}
// Create the first browser window.
CefBrowserHost::CreateBrowser(window_info, handler.get(), url,
browser_settings, NULL);
}<commit_msg>Change URL<commit_after>// Copyright (c) 2013 The Chromium Embedded Framework 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 "cefsimple/simple_app.h"
#include <string>
#include "cefsimple/simple_handler.h"
#include "include/cef_browser.h"
#include "include/cef_command_line.h"
#include "include/wrapper/cef_helpers.h"
#include <shlwapi.h>
#include <fstream>
HWND SimpleApp::gameWindow = 0;
SimpleApp::SimpleApp() {
}
void GetDesktopResolution(int& horizontal, int& vertical)
{
RECT desktop;
const HWND hDesktop = GetDesktopWindow();
GetWindowRect(hDesktop, &desktop);
horizontal = desktop.right;
vertical = desktop.bottom;
}
void SimpleApp::OnContextInitialized() {
CEF_REQUIRE_UI_THREAD();
// Information used when creating the native window.
CefWindowInfo window_info;
#if defined(OS_WIN)
// On Windows we need to specify certain flags that will be passed to
// CreateWindowEx().
window_info.SetAsPopup(NULL, "Custom Menu");
#endif
int horizontal, vertical;
GetDesktopResolution(horizontal, vertical);
window_info.width = horizontal - 100;
window_info.height = vertical - 100;
int xPos = (horizontal - window_info.width) / 2;
int yPos = (vertical - window_info.height) / 2;
window_info.x = xPos;
window_info.y = yPos;
// SimpleHandler implements browser-level callbacks.
CefRefPtr<SimpleHandler> handler(new SimpleHandler());
// Specify CEF browser settings here.
CefBrowserSettings browser_settings;
wchar_t pathToOurDirectory[260];
GetModuleFileName(NULL, pathToOurDirectory, 260);
PathRemoveFileSpec(pathToOurDirectory);
std::wstring path(pathToOurDirectory);
path.append(L"\\mods\\menus\\default");
CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager(NULL);
manager->SetStoragePath(path, true, NULL);
CefRefPtr<CefCommandLine> command_line = CefCommandLine::GetGlobalCommandLine();
std::wstring url = L"http://eldewrito.github.io/menu/";
std::wstring urlString = command_line->GetSwitchValue("url").ToWString();
if (!urlString.empty())
{
url = urlString;
}
std::string hwndString = command_line->GetSwitchValue("hwnd").ToString();
if (!hwndString.empty())
{
gameWindow = (HWND)stoi(hwndString);
ShowWindow(gameWindow, SW_HIDE);
}
else
{
CefShutdown();
}
// Create the first browser window.
CefBrowserHost::CreateBrowser(window_info, handler.get(), url,
browser_settings, NULL);
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: SlideSorterViewShell.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2005-07-14 10:13:09 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifndef SD_SLIDESORTER_SLIDE_SORTER_VIEW_SHELL_HXX
#define SD_SLIDESORTER_SLIDE_SORTER_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#include "SlideSorterViewShell.hxx"
#include "glob.hxx"
#ifndef _SFX_SHELL_HXX
#include <sfx2/shell.hxx>
#endif
#ifndef _VIEWFAC_HXX
#include <sfx2/viewfac.hxx>
#endif
class ScrollBarBox;
class TabBar;
class Window;
namespace sd { namespace slidesorter { namespace model {
class SlideSorterModel;
} } }
namespace sd { namespace slidesorter { namespace view {
class SlideSorterView;
} } }
namespace sd { namespace slidesorter { namespace controller {
class Listener;
class SlideSorterController;
class SlotManager;
} } }
namespace sd { namespace slidesorter {
class SlideSorterViewShell
: public ViewShell
{
friend class controller::SlotManager;
public:
TYPEINFO();
SFX_DECL_INTERFACE(SD_IF_SDSLIDESORTERVIEWSHELL);
enum TabBarEntry
{
TBE_SWITCH = 0,
TBE_SLIDES = 1,
TBE_MASTER_PAGES = 2
};
static SfxShell* CreateInstance (
sal_Int32 nId,
SfxShell* pParent,
void* pUserData,
ViewShellBase& rBase);
SlideSorterViewShell (
SfxViewFrame* pFrame,
ViewShellBase& rViewShellBase,
::Window* pParentWindow,
FrameView* pFrameView);
virtual ~SlideSorterViewShell (void);
/** Late initialization that has to be called after a new instance has
completed its construction.
*/
virtual void Init (void);
/** Return a slide sorter that is currently displayed in one of the
panes that belong to the given ViewShellBase object.
When there is only one slide sorter visible then that one is
returned. When two (or more) are visible then the one in the center
pane is returned. When no slidesorter is visible then NULL is
returned.
*/
static SlideSorterViewShell* GetSlideSorter (ViewShellBase& rBase);
virtual void GetFocus (void);
virtual void LoseFocus (void);
virtual SdPage* GetActualPage (void);
/// inherited from sd::ViewShell
virtual SdPage* getCurrentPage() const;
void ExecCtrl (SfxRequest& rRequest);
virtual void GetCtrlState (SfxItemSet &rSet);
virtual void FuSupport (SfxRequest& rRequest);
virtual void FuTemporary (SfxRequest& rRequest);
virtual void GetStatusBarState (SfxItemSet& rSet);
virtual void FuPermanent (SfxRequest& rRequest);
void GetAttrState (SfxItemSet& rSet);
void ExecStatusBar (SfxRequest& rRequest);
virtual void Command (const CommandEvent& rEvent, ::sd::Window* pWindow);
virtual void GetMenuState (SfxItemSet &rSet);
virtual void ReadFrameViewData (FrameView* pView);
virtual void WriteFrameViewData (void);
/** The UI features are used for selective display of tool bars
depending on whether the slide sorter is the main view or not.
@param nFeature
Valid values are defined (and used) in the implementation file.
*/
virtual BOOL HasUIFeature (ULONG nFeature);
/** Set the zoom factor. The given value is clipped against an upper
bound.
@param nZoom
An integer percent value, i.e. nZoom/100 is the actual zoom
factor.
*/
virtual void SetZoom (long int nZoom);
virtual void SetZoomRect (const Rectangle& rZoomRect);
/** This is a callback method used by the active window to delegate its
Paint() call to. This view shell itself delegates it to the view.
*/
virtual void Paint(const Rectangle& rRect, ::sd::Window* pWin);
/** Place and size the controls and windows. You may want to call this
method when something has changed that for instance affects the
visibility state of the scroll bars.
*/
virtual void ArrangeGUIElements (void);
/** Return the control of the vertical scroll bar.
*/
ScrollBar* GetVerticalScrollBar (void) const;
/** Return the control of the horizontal scroll bar.
*/
ScrollBar* GetHorizontalScrollBar (void) const;
/** Return the scroll bar filler that paints the little square that is
enclosed by the two scroll bars.
*/
ScrollBarBox* GetScrollBarFiller (void) const;
/** Set the tab bar to the given mode.
@param eEntry
When TBE_SWITCH is given, then switch between the two tabs.
*/
TabBarEntry SwitchTabBar (TabBarEntry eEntry);
controller::SlideSorterController& GetSlideSorterController (void);
//===== Drag and Drop =====================================================
virtual void StartDrag (
const Point& rDragPt,
::Window* pWindow );
virtual void DragFinished (
sal_Int8 nDropAction);
virtual sal_Int8 AcceptDrop (
const AcceptDropEvent& rEvt,
DropTargetHelper& rTargetHelper,
::sd::Window* pTargetWindow = NULL,
USHORT nPage = SDRPAGE_NOTFOUND,
USHORT nLayer = SDRPAGE_NOTFOUND );
virtual sal_Int8 ExecuteDrop (
const ExecuteDropEvent& rEvt,
DropTargetHelper& rTargetHelper,
::sd::Window* pTargetWindow = NULL,
USHORT nPage = SDRPAGE_NOTFOUND,
USHORT nLayer = SDRPAGE_NOTFOUND);
/** Return the selected pages by putting them into the given container.
The container does not have to be empty. It is not cleared.
*/
void GetSelectedPages (::std::vector<SdPage*>& pPageContainer);
/** Add a listener that is called when the selection of the slide sorter
changes.
@param rListener
When this method is called multiple times for the same listener
the second and all following calls are ignored. Each listener
is added only once.
*/
void AddSelectionChangeListener (const Link& rListener);
/** Remove a listener that was called when the selection of the slide
sorter changes.
@param rListener
It is save to pass a listener that was not added are has been
removed previously. Such calls are ignored.
*/
void RemoveSelectionChangeListener (const Link& rListener);
virtual DrawController* GetController (void);
/** Create an accessible object representing the specified window.
@param pWindow
The returned object makes the document displayed in this window
accessible.
@return
Returns an <type>AccessibleSlideSorterView</type> object.
*/
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>
CreateAccessibleDocumentView (::sd::Window* pWindow);
protected:
::std::auto_ptr<controller::SlideSorterController> mpSlideSorterController;
::std::auto_ptr<model::SlideSorterModel> mpSlideSorterModel;
::std::auto_ptr<view::SlideSorterView> mpSlideSorterView;
virtual SvBorder GetBorder (bool bOuterResize);
/** This virtual method makes it possible to create a specialization of
the slide sorter view shell that works with its own implementation
of model, view, and controller. The default implementation simply
calls the CreateModel(), CreateView(), and CreateController()
methods in this order.
*/
virtual void CreateModelViewController (void);
/** Create the model for the view shell. When called from the default
implementation of CreateModelViewController() then neither view nor
controller do exist. Test their pointers when in doubt.
*/
virtual model::SlideSorterModel* CreateModel (void);
/** Create the view for the view shell. When called from the default
implementation of CreateModelViewController() then the model but not
the controller does exist. Test their pointers when in doubt.
*/
virtual view::SlideSorterView* CreateView (void);
/** Create the controller for the view shell. When called from the default
implementation of CreateModelViewController() then both the view and
the controller do exist. Test their pointers when in doubt.
*/
virtual controller::SlideSorterController* CreateController (void);
private:
::std::auto_ptr<TabBar> mpTabBar;
/** Set this flag to <TRUE/> to force a layout before the next paint.
*/
bool mbLayoutPending;
/** Create the controls for the slide sorter. This are the tab bar
for switching the edit mode, the scroll bar, and the actual
slide sorter view window.
This method is usually called exactly one time from the
constructor.
*/
void SetupControls (::Window* pParentWindow);
/** This method is usually called exactly one time from the
constructor.
*/
void SetupListeners (void);
/** Release the listeners that have been installed in SetupListeners().
*/
void ReleaseListeners (void);
/** This method overwrites the one from our base class: We do our own
scroll bar and the base class call is thus unnecessary. It simply
calls UpdateScrollBars(false).
*/
virtual void UpdateScrollBars (void);
};
} } // end of namespace ::sd::slidesorter
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.62); FILE MERGED 2005/09/05 13:22:48 rt 1.6.62.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlideSorterViewShell.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:15:24 $
*
* 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 SD_SLIDESORTER_SLIDE_SORTER_VIEW_SHELL_HXX
#define SD_SLIDESORTER_SLIDE_SORTER_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#include "SlideSorterViewShell.hxx"
#include "glob.hxx"
#ifndef _SFX_SHELL_HXX
#include <sfx2/shell.hxx>
#endif
#ifndef _VIEWFAC_HXX
#include <sfx2/viewfac.hxx>
#endif
class ScrollBarBox;
class TabBar;
class Window;
namespace sd { namespace slidesorter { namespace model {
class SlideSorterModel;
} } }
namespace sd { namespace slidesorter { namespace view {
class SlideSorterView;
} } }
namespace sd { namespace slidesorter { namespace controller {
class Listener;
class SlideSorterController;
class SlotManager;
} } }
namespace sd { namespace slidesorter {
class SlideSorterViewShell
: public ViewShell
{
friend class controller::SlotManager;
public:
TYPEINFO();
SFX_DECL_INTERFACE(SD_IF_SDSLIDESORTERVIEWSHELL);
enum TabBarEntry
{
TBE_SWITCH = 0,
TBE_SLIDES = 1,
TBE_MASTER_PAGES = 2
};
static SfxShell* CreateInstance (
sal_Int32 nId,
SfxShell* pParent,
void* pUserData,
ViewShellBase& rBase);
SlideSorterViewShell (
SfxViewFrame* pFrame,
ViewShellBase& rViewShellBase,
::Window* pParentWindow,
FrameView* pFrameView);
virtual ~SlideSorterViewShell (void);
/** Late initialization that has to be called after a new instance has
completed its construction.
*/
virtual void Init (void);
/** Return a slide sorter that is currently displayed in one of the
panes that belong to the given ViewShellBase object.
When there is only one slide sorter visible then that one is
returned. When two (or more) are visible then the one in the center
pane is returned. When no slidesorter is visible then NULL is
returned.
*/
static SlideSorterViewShell* GetSlideSorter (ViewShellBase& rBase);
virtual void GetFocus (void);
virtual void LoseFocus (void);
virtual SdPage* GetActualPage (void);
/// inherited from sd::ViewShell
virtual SdPage* getCurrentPage() const;
void ExecCtrl (SfxRequest& rRequest);
virtual void GetCtrlState (SfxItemSet &rSet);
virtual void FuSupport (SfxRequest& rRequest);
virtual void FuTemporary (SfxRequest& rRequest);
virtual void GetStatusBarState (SfxItemSet& rSet);
virtual void FuPermanent (SfxRequest& rRequest);
void GetAttrState (SfxItemSet& rSet);
void ExecStatusBar (SfxRequest& rRequest);
virtual void Command (const CommandEvent& rEvent, ::sd::Window* pWindow);
virtual void GetMenuState (SfxItemSet &rSet);
virtual void ReadFrameViewData (FrameView* pView);
virtual void WriteFrameViewData (void);
/** The UI features are used for selective display of tool bars
depending on whether the slide sorter is the main view or not.
@param nFeature
Valid values are defined (and used) in the implementation file.
*/
virtual BOOL HasUIFeature (ULONG nFeature);
/** Set the zoom factor. The given value is clipped against an upper
bound.
@param nZoom
An integer percent value, i.e. nZoom/100 is the actual zoom
factor.
*/
virtual void SetZoom (long int nZoom);
virtual void SetZoomRect (const Rectangle& rZoomRect);
/** This is a callback method used by the active window to delegate its
Paint() call to. This view shell itself delegates it to the view.
*/
virtual void Paint(const Rectangle& rRect, ::sd::Window* pWin);
/** Place and size the controls and windows. You may want to call this
method when something has changed that for instance affects the
visibility state of the scroll bars.
*/
virtual void ArrangeGUIElements (void);
/** Return the control of the vertical scroll bar.
*/
ScrollBar* GetVerticalScrollBar (void) const;
/** Return the control of the horizontal scroll bar.
*/
ScrollBar* GetHorizontalScrollBar (void) const;
/** Return the scroll bar filler that paints the little square that is
enclosed by the two scroll bars.
*/
ScrollBarBox* GetScrollBarFiller (void) const;
/** Set the tab bar to the given mode.
@param eEntry
When TBE_SWITCH is given, then switch between the two tabs.
*/
TabBarEntry SwitchTabBar (TabBarEntry eEntry);
controller::SlideSorterController& GetSlideSorterController (void);
//===== Drag and Drop =====================================================
virtual void StartDrag (
const Point& rDragPt,
::Window* pWindow );
virtual void DragFinished (
sal_Int8 nDropAction);
virtual sal_Int8 AcceptDrop (
const AcceptDropEvent& rEvt,
DropTargetHelper& rTargetHelper,
::sd::Window* pTargetWindow = NULL,
USHORT nPage = SDRPAGE_NOTFOUND,
USHORT nLayer = SDRPAGE_NOTFOUND );
virtual sal_Int8 ExecuteDrop (
const ExecuteDropEvent& rEvt,
DropTargetHelper& rTargetHelper,
::sd::Window* pTargetWindow = NULL,
USHORT nPage = SDRPAGE_NOTFOUND,
USHORT nLayer = SDRPAGE_NOTFOUND);
/** Return the selected pages by putting them into the given container.
The container does not have to be empty. It is not cleared.
*/
void GetSelectedPages (::std::vector<SdPage*>& pPageContainer);
/** Add a listener that is called when the selection of the slide sorter
changes.
@param rListener
When this method is called multiple times for the same listener
the second and all following calls are ignored. Each listener
is added only once.
*/
void AddSelectionChangeListener (const Link& rListener);
/** Remove a listener that was called when the selection of the slide
sorter changes.
@param rListener
It is save to pass a listener that was not added are has been
removed previously. Such calls are ignored.
*/
void RemoveSelectionChangeListener (const Link& rListener);
virtual DrawController* GetController (void);
/** Create an accessible object representing the specified window.
@param pWindow
The returned object makes the document displayed in this window
accessible.
@return
Returns an <type>AccessibleSlideSorterView</type> object.
*/
virtual ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>
CreateAccessibleDocumentView (::sd::Window* pWindow);
protected:
::std::auto_ptr<controller::SlideSorterController> mpSlideSorterController;
::std::auto_ptr<model::SlideSorterModel> mpSlideSorterModel;
::std::auto_ptr<view::SlideSorterView> mpSlideSorterView;
virtual SvBorder GetBorder (bool bOuterResize);
/** This virtual method makes it possible to create a specialization of
the slide sorter view shell that works with its own implementation
of model, view, and controller. The default implementation simply
calls the CreateModel(), CreateView(), and CreateController()
methods in this order.
*/
virtual void CreateModelViewController (void);
/** Create the model for the view shell. When called from the default
implementation of CreateModelViewController() then neither view nor
controller do exist. Test their pointers when in doubt.
*/
virtual model::SlideSorterModel* CreateModel (void);
/** Create the view for the view shell. When called from the default
implementation of CreateModelViewController() then the model but not
the controller does exist. Test their pointers when in doubt.
*/
virtual view::SlideSorterView* CreateView (void);
/** Create the controller for the view shell. When called from the default
implementation of CreateModelViewController() then both the view and
the controller do exist. Test their pointers when in doubt.
*/
virtual controller::SlideSorterController* CreateController (void);
private:
::std::auto_ptr<TabBar> mpTabBar;
/** Set this flag to <TRUE/> to force a layout before the next paint.
*/
bool mbLayoutPending;
/** Create the controls for the slide sorter. This are the tab bar
for switching the edit mode, the scroll bar, and the actual
slide sorter view window.
This method is usually called exactly one time from the
constructor.
*/
void SetupControls (::Window* pParentWindow);
/** This method is usually called exactly one time from the
constructor.
*/
void SetupListeners (void);
/** Release the listeners that have been installed in SetupListeners().
*/
void ReleaseListeners (void);
/** This method overwrites the one from our base class: We do our own
scroll bar and the base class call is thus unnecessary. It simply
calls UpdateScrollBars(false).
*/
virtual void UpdateScrollBars (void);
};
} } // end of namespace ::sd::slidesorter
#endif
<|endoftext|> |
<commit_before>///
/// @file Pk.cpp
///
/// Copyright (C) 2013 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include "pi_bsearch.h"
#include "isqrt.h"
#include <primesieve/soe/PrimeSieve.h>
#include <stdint.h>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#include "to_omp_threads.h"
#endif
namespace primecount {
/// 2nd partial sieve function.
/// P2(x, a) counts the numbers <= x that have exactly 2 prime
/// factors each exceeding the a-th prime.
///
int64_t P2(int64_t x, int64_t a, int64_t b, int threads)
{
int64_t sum = -((b + a - 2) * (b - a + 1) / 2);
int64_t pix = 0;
std::vector<int32_t> primes;
std::vector<int64_t> counts;
PrimeSieve ps;
ps.generate_N_Primes(b, &primes);
counts.resize(primes.size());
// This uses a clever trick, instead of calculating
// pi(x / primes[i]) for a < i <= b it only counts the primes
// between adjacent values [x / primes[i], x / primes[i - 1]].
// When finished pi(x / primes[i]) can quickly be calculated
// by backwards summing up the counts.
//
#ifdef _OPENMP
threads = to_omp_threads(threads);
#pragma omp parallel for private(ps) schedule(dynamic) num_threads(threads)
#endif
for (int64_t i = b; i > a; i--)
{
int64_t x2 = (i != b) ? x / primes[i] + 1 : 0;
int64_t x3 = x / primes[i - 1];
counts[i - 1] = ps.countPrimes(x2, x3);
}
for (int64_t i = b; i > a; i--)
{
pix += counts[i - 1];
sum += pix;
}
return sum;
}
/// 3rd partial sieve function.
/// P3(x, a) counts the numbers <= x that have exactly 3 prime
/// factors each exceeding the a-th prime.
///
int64_t P3(int64_t x, int64_t a, int64_t b, int64_t c, int threads)
{
std::vector<int32_t> primes;
PrimeSieve ps;
ps.generate_N_Primes(b, &primes);
int64_t sum = 0;
#ifdef _OPENMP
threads = to_omp_threads(threads);
#pragma omp parallel for reduction(+: sum) schedule(dynamic) num_threads(threads)
#endif
for (int64_t i = a + 1; i <= c; i++)
{
int64_t x2 = x / primes[i - 1];
int64_t bi = pi_bsearch(primes.begin(), primes.end(), isqrt(x2));
int64_t sum2 = 0;
for (int64_t j = i; j <= bi; j++)
sum2 += pi_bsearch(primes.begin(), primes.end(), x2 / primes[j - 1]) - (j - 1);
sum += sum2;
}
return sum;
}
} // namespace primecount
<commit_msg>improved code readability<commit_after>///
/// @file Pk.cpp
///
/// Copyright (C) 2013 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include "pi_bsearch.h"
#include "isqrt.h"
#include <primesieve/soe/PrimeSieve.h>
#include <stdint.h>
#include <vector>
#ifdef _OPENMP
#include <omp.h>
#include "to_omp_threads.h"
#endif
namespace primecount {
/// 2nd partial sieve function.
/// P2(x, a) counts the numbers <= x that have exactly 2 prime
/// factors each exceeding the a-th prime.
///
int64_t P2(int64_t x, int64_t a, int64_t b, int threads)
{
int64_t pix = 0;
int64_t sum = -((b + a - 2) * (b - a + 1) / 2);
std::vector<int32_t> primes;
std::vector<int64_t> counts;
PrimeSieve ps;
ps.generate_N_Primes(b, &primes);
counts.resize(primes.size());
// This uses a clever trick, instead of calculating
// pi(x / primes[i]) for a < i <= b it only counts the primes
// between adjacent values [x / primes[i], x / primes[i - 1]].
// When finished pi(x / primes[i]) can quickly be calculated
// by backwards summing up the counts.
//
#ifdef _OPENMP
threads = to_omp_threads(threads);
#pragma omp parallel for private(ps) schedule(dynamic) num_threads(threads)
#endif
for (int64_t i = b; i > a; i--)
{
int64_t x2 = (i != b) ? x / primes[i] + 1 : 0;
int64_t x3 = x / primes[i - 1];
counts[i - 1] = ps.countPrimes(x2, x3);
}
for (int64_t i = b; i > a; i--)
{
pix += counts[i - 1];
sum += pix;
}
return sum;
}
/// 3rd partial sieve function.
/// P3(x, a) counts the numbers <= x that have exactly 3 prime
/// factors each exceeding the a-th prime.
///
int64_t P3(int64_t x, int64_t a, int64_t b, int64_t c, int threads)
{
std::vector<int32_t> primes;
PrimeSieve ps;
ps.generate_N_Primes(b, &primes);
int64_t sum = 0;
#ifdef _OPENMP
threads = to_omp_threads(threads);
#pragma omp parallel for reduction(+: sum) schedule(dynamic) num_threads(threads)
#endif
for (int64_t i = a + 1; i <= c; i++)
{
int64_t x2 = x / primes[i - 1];
int64_t bi = pi_bsearch(primes.begin(), primes.end(), isqrt(x2));
for (int64_t j = i; j <= bi; j++)
sum += pi_bsearch(primes.begin(), primes.end(), x2 / primes[j - 1]) - (j - 1);
}
return sum;
}
} // namespace primecount
<|endoftext|> |
<commit_before><commit_msg>Removed extra slash when defining model path<commit_after><|endoftext|> |
<commit_before><commit_msg>HTCONDOR-969 Add missing newline to ded sched dprintf<commit_after><|endoftext|> |
<commit_before>/****************************************************************
Purpose:
Look for a "core" file at a given location. Return TRUE if it
exists and appears complete and correct, and FALSE otherwise.
The SUN core consists of a header, the data and stack segments
and finally the uarea. We check the magic number in the header
first. If that's OK we then calculate what the size of the
core should be using the size of the header, the sizes of the
data and stack areas recorded in the header and the size of the
uarea as defined in "sys/param.h". We then compare this
calculation with the actual size of the file.
Portability:
This code depends upon the core format for SUNOS4.1 systems,
and is not portable to other systems.
Modified for Solaris by : Dhaval N. Shah
University of Wisconsin, Madison
** Computer Sciences Department
******************************************************************/
#define _ALL_SOURCE
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_constants.h"
#include "condor_jobqueue.h"
#include <sys/file.h>
#include <sys/core.h>
#include <sys/param.h>
#include "proto.h"
static char *_FileName_ = __FILE__; /* Used by EXCEPT (see except.h) */
#if defined(Solaris)
#define UPAGES 4
#define NBPG 0x1000 /*couldnt get this val from header files. Rough
estimate from Suns header files - Raghu */
#endif
const int UAREA_SIZE = UPAGES * NBPG;
const int HEADER_SIZE = sizeof(struct core);
int
core_is_valid( char *name )
{
struct core header;
int fd;
int total_size;
off_t file_size;
dprintf( D_ALWAYS,
"Analyzing core file \"%s\" for existence and completeness\n", name
);
if( (fd=open(name,O_RDONLY)) < 0 ) {
dprintf( D_ALWAYS, "Can't open core file \"%s\"", name );
return FALSE;
}
if( read(fd,(char *)&header,HEADER_SIZE) != HEADER_SIZE ) {
dprintf( D_ALWAYS, "Can't read header from core file\n" );
(void)close( fd );
return FALSE;
}
file_size = lseek( fd, (off_t)0, SEEK_END );
(void)close( fd );
if( header.c_magic != CORE_MAGIC ) {
dprintf( D_ALWAYS,
"Core file - bad magic number (0x%x)\n", header.c_magic
);
return FALSE;
}
dprintf( D_ALWAYS,
"Core file - magic number OK\n"
);
total_size = header.c_len + header.c_dsize + header.c_ssize + UAREA_SIZE;
if( file_size != total_size ) {
dprintf( D_ALWAYS,
"file_size should be %d, but is %d\n", total_size, file_size
);
return FALSE;
} else {
dprintf( D_ALWAYS,
"Core file_size of %d is correct\n", file_size
);
return TRUE;
}
#if 0
dprintf( D_ALWAYS, "c_len = %d bytes\n", header.c_len );
dprintf( D_ALWAYS, "c_dsize = %d bytes\n", header.c_dsize );
dprintf( D_ALWAYS, "c_ssize = %d bytes\n", header.c_ssize );
dprintf( D_ALWAYS, "UAREA_SIZE = %d bytes\n", UAREA_SIZE );
dprintf( D_ALWAYS, "total_size = %d bytes\n", total_size );
#endif
}
<commit_msg>Modified to check for correct magic number for Solaris core files.<commit_after>/****************************************************************
Purpose:
Look for a "core" file at a given location. Return TRUE if it
exists and appears complete and correct, and FALSE otherwise.
The SUN core consists of a header, the data and stack segments
and finally the uarea. We check the magic number in the header
first. If that's OK we then calculate what the size of the
core should be using the size of the header, the sizes of the
data and stack areas recorded in the header and the size of the
uarea as defined in "sys/param.h". We then compare this
calculation with the actual size of the file.
Portability:
This code depends upon the core format for SUNOS4.1 systems,
and is not portable to other systems.
Modified for Solaris by : Dhaval N. Shah
University of Wisconsin, Madison
** Computer Sciences Department
******************************************************************/
#define _ALL_SOURCE
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_constants.h"
#include "condor_jobqueue.h"
#include <sys/file.h>
#include <sys/core.h>
#include <sys/param.h>
#include "proto.h"
static char *_FileName_ = __FILE__; /* Used by EXCEPT (see except.h) */
#if defined(Solaris)
#define UPAGES 4
#define NBPG 0x1000 /*couldnt get this val from header files. Rough
estimate from Suns header files - Raghu */
#undef CORE_MAGIC
#define CORE_MAGIC 0x7f454c46 /* at least, this is the magic for my
core file - Jim B. */
#endif
const int UAREA_SIZE = UPAGES * NBPG;
const int HEADER_SIZE = sizeof(struct core);
int
core_is_valid( char *name )
{
struct core header;
int fd;
int total_size;
off_t file_size;
dprintf( D_ALWAYS,
"Analyzing core file \"%s\" for existence and completeness\n", name
);
if( (fd=open(name,O_RDONLY)) < 0 ) {
dprintf( D_ALWAYS, "Can't open core file \"%s\"", name );
return FALSE;
}
if( read(fd,(char *)&header,HEADER_SIZE) != HEADER_SIZE ) {
dprintf( D_ALWAYS, "Can't read header from core file\n" );
(void)close( fd );
return FALSE;
}
file_size = lseek( fd, (off_t)0, SEEK_END );
(void)close( fd );
if( header.c_magic != CORE_MAGIC ) {
dprintf( D_ALWAYS,
"Core file - bad magic number (0x%x)\n", header.c_magic
);
return FALSE;
}
dprintf( D_ALWAYS,
"Core file - magic number OK\n"
);
/* the size test is bogus on Solaris -- there is something wrong
with the header information -- I'm taking it out. -Jim B. */
/* total_size = header.c_len + header.c_dsize + header.c_ssize + UAREA_SIZE;
if( file_size != total_size ) {
dprintf( D_ALWAYS,
"file_size should be %d, but is %d\n", total_size, file_size
);
return FALSE;
} else {
dprintf( D_ALWAYS,
"Core file_size of %d is correct\n", file_size
); */
return TRUE;
/* } */
#if 0
dprintf( D_ALWAYS, "c_len = %d bytes\n", header.c_len );
dprintf( D_ALWAYS, "c_dsize = %d bytes\n", header.c_dsize );
dprintf( D_ALWAYS, "c_ssize = %d bytes\n", header.c_ssize );
dprintf( D_ALWAYS, "UAREA_SIZE = %d bytes\n", UAREA_SIZE );
dprintf( D_ALWAYS, "total_size = %d bytes\n", total_size );
#endif
}
<|endoftext|> |
<commit_before><commit_msg>Introduce QML_FBO_FLUSH_BEFORE_DETACH to work around FBO issue.<commit_after><|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS warnings01 (1.2.16); FILE MERGED 2005/10/21 09:48:58 dbo 1.2.16.1: #i53898# warning free code<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <memory>
#include <set>
#include <string>
#include <gemmi/cif.hpp>
#include <gemmi/mmcif.hpp>
#include "cif.hh"
struct ModelDiscriminator {
ModelDiscriminator(const std::string &model_name,
const int model_col = 11)
: _model_name(model_name), _model_col(model_col)
{
}
bool operator()(const gemmi::cif::Table::Row &site) const
{
return _model_name != site[_model_col];
}
private:
const std::string _model_name;
int _model_col;
};
struct ModelSetDiscriminator {
ModelSetDiscriminator(const std::set<int> models,
const int model_col = 11)
: _models(models), _model_col(model_col)
{
}
bool operator()(const gemmi::cif::Table::Row &site) const
{
return _models.count(std::stoi(site[_model_col])) == 0;
}
private:
const std::set<int> _models;
int _model_col;
};
struct ChainDiscriminator {
ChainDiscriminator(const std::string &model_name, const std::string &chain_name,
const int model_col = 11, const int chain_col = 1)
: _model_name(model_name), _chain_name(chain_name),
_model_col(model_col), _chain_col(chain_col)
{
}
bool operator()(const gemmi::cif::Table::Row &site) const
{
return _model_name != site[_model_col] || _chain_name != site[_chain_col];
}
private:
const std::string _model_name, _chain_name;
int _model_col, _chain_col;
};
static std::unique_ptr<std::set<int>>
get_models(const gemmi::cif::Document &doc)
{
auto models = std::make_unique<std::set<int>>();
for (auto block : doc.blocks) {
for (auto site : block.find("_atom_site.", {"pdbx_PDB_model_num"})) {
models->insert(gemmi::cif::as_int(site[0]));
}
}
return models;
}
static std::unique_ptr<std::set<std::string>>
get_chains(const gemmi::cif::Document &doc)
{
auto chains = std::make_unique<std::set<std::string>>();
for (auto block : doc.blocks) {
for (auto site : block.find("_atom_site.", {"auth_asym_id"})) {
chains->insert(site[0]);
}
}
return chains;
}
static std::unique_ptr<std::set<std::string>>
get_chains(const gemmi::Model &model)
{
auto chains = std::make_unique<std::set<std::string>>();
for (auto &chain : model.chains) {
chains->insert(chain.name);
}
return chains;
}
static const auto atom_site_columns = std::vector<std::string>({
"group_PDB",
"auth_asym_id",
"auth_seq_id",
"pdbx_PDB_ins_code",
"auth_comp_id",
"auth_atom_id",
"label_alt_id",
"type_symbol",
"Cartn_x",
"Cartn_y",
"Cartn_z",
"pdbx_PDB_model_num",
});
static freesasa_cif_atom
freesasa_atom_from_site(const gemmi::cif::Table::Row &site)
{
std::unique_ptr<std::string> auth_atom_id;
// remove quotation marks if necessary
if (site[5][0] == '"') {
auth_atom_id = std::make_unique<std::string>(site[5].substr(1, site[5].size() - 2));
} else {
auth_atom_id = std::make_unique<std::string>(site[5]);
}
return {
.group_PDB = site[0].c_str(),
.auth_asym_id = site[1][0],
.auth_seq_id = site[2].c_str(),
.pdbx_PDB_ins_code = site[3].c_str(),
.auth_comp_id = site[4].c_str(),
.auth_atom_id = std::move(*auth_atom_id).c_str(),
.label_alt_id = site[6].c_str(),
.type_symbol = site[7].c_str(),
.Cartn_x = atof(site[8].c_str()),
.Cartn_y = atof(site[9].c_str()),
.Cartn_z = atof(site[10].c_str())};
}
template <typename T>
static freesasa_structure *
freesasa_structure_from_pred(const gemmi::cif::Document &doc,
const T &discriminator,
const freesasa_classifier *classifier,
int structure_options)
{
freesasa_structure *structure = freesasa_structure_new();
std::string auth_atom_id;
for (auto block : doc.blocks) {
for (auto site : block.find("_atom_site.", atom_site_columns)) {
if (site[0] != "ATOM" && !(structure_options & FREESASA_INCLUDE_HETATM)) {
continue;
}
if (discriminator(site)) continue;
freesasa_cif_atom atom = freesasa_atom_from_site(site);
if (!(structure_options & FREESASA_INCLUDE_HYDROGEN) && std::string(atom.type_symbol) == "H") {
continue;
}
// Pick the first alternative conformation for an atom
auto currentAltId = site[6][0];
if (currentAltId != '.' && currentAltId != 'A') {
continue;
}
freesasa_structure_add_cif_atom(structure, &atom, classifier, structure_options);
}
}
return structure;
}
freesasa_structure *
freesasa_structure_from_cif(std::FILE *input,
const freesasa_classifier *classifier,
int structure_options)
{
const auto doc = gemmi::cif::read_cstream(input, 8192, "cif-input");
const auto models = get_models(doc);
std::unique_ptr<const ModelSetDiscriminator> discriminator;
if (structure_options & FREESASA_JOIN_MODELS) {
discriminator = std::make_unique<const ModelSetDiscriminator>(std::move(*models));
} else {
auto firstModel = models->begin();
auto singleModel = std::set<int>{*firstModel};
discriminator = std::make_unique<const ModelSetDiscriminator>(singleModel);
}
return freesasa_structure_from_pred(doc, *discriminator, classifier, structure_options);
}
freesasa_structure *
freesasa_structure_from_model(const gemmi::cif::Document &doc,
const std::string &model_name,
const freesasa_classifier *classifier,
int structure_options)
{
const ModelDiscriminator discriminator(model_name);
return freesasa_structure_from_pred(doc, discriminator, classifier, structure_options);
freesasa_structure *structure = freesasa_structure_new();
}
freesasa_structure *
freesasa_structure_from_chain(const gemmi::cif::Document doc,
const std::string &model_name,
const std::string &chain_name,
const freesasa_classifier *classifier,
int structure_options)
{
const ChainDiscriminator discriminator(model_name, chain_name);
return freesasa_structure_from_pred(doc, discriminator, classifier, structure_options);
}
std::vector<freesasa_structure *>
freesasa_cif_structure_array(std::FILE *input,
int *n,
const freesasa_classifier *classifier,
int options)
{
int n_models = 0, n_chains = 0;
std::vector<freesasa_structure *> ss;
const auto doc = gemmi::cif::read_cstream(input, 8192, "cif-input");
gemmi::Structure gemmi_struct = gemmi::make_structure_from_block(doc.blocks[0]);
const auto models = gemmi_struct.models;
n_models = models.size();
/* only keep first model if option not provided */
if (!(options & FREESASA_SEPARATE_MODELS)) n_models = 1;
/* for each model read chains if requested */
if (options & FREESASA_SEPARATE_CHAINS) {
for (int i = 0; i < n_models; ++i) {
auto chain_names = get_chains(models[i]);
int n_new_chains = chain_names->size();
n_chains += n_new_chains;
if (n_new_chains == 0) {
freesasa_warn("in %s(): no chains found (in model %s)", __func__, models[i].name.c_str());
continue;
}
ss.reserve(n_new_chains);
for (auto &chain_name : *chain_names) {
ss.emplace_back(
freesasa_structure_from_chain(doc, models[i].name, chain_name, classifier, options));
freesasa_structure_set_model(ss.back(), i + 1);
}
}
if (n_chains == 0) freesasa_fail("In %s(): No chains in any model in protein: %s.", __func__, gemmi_struct.name.c_str());
*n = n_chains;
} else {
ss.reserve(n_models);
for (int i = 0; i < n_models; ++i) {
ss.emplace_back(
freesasa_structure_from_model(doc, models[i].name, classifier, options));
freesasa_structure_set_model(ss.back(), i + 1);
}
*n = n_models;
}
return ss;
}
<commit_msg>Removed copying/allocating memory of auth_atom_id for atoms lacking (")<commit_after>#include <iostream>
#include <memory>
#include <set>
#include <string>
#include <gemmi/cif.hpp>
#include <gemmi/mmcif.hpp>
#include "cif.hh"
struct ModelDiscriminator {
ModelDiscriminator(const std::string &model_name,
const int model_col = 11)
: _model_name(model_name), _model_col(model_col)
{
}
bool operator()(const gemmi::cif::Table::Row &site) const
{
return _model_name != site[_model_col];
}
private:
const std::string _model_name;
int _model_col;
};
struct ModelSetDiscriminator {
ModelSetDiscriminator(const std::set<int> models,
const int model_col = 11)
: _models(models), _model_col(model_col)
{
}
bool operator()(const gemmi::cif::Table::Row &site) const
{
return _models.count(std::stoi(site[_model_col])) == 0;
}
private:
const std::set<int> _models;
int _model_col;
};
struct ChainDiscriminator {
ChainDiscriminator(const std::string &model_name, const std::string &chain_name,
const int model_col = 11, const int chain_col = 1)
: _model_name(model_name), _chain_name(chain_name),
_model_col(model_col), _chain_col(chain_col)
{
}
bool operator()(const gemmi::cif::Table::Row &site) const
{
return _model_name != site[_model_col] || _chain_name != site[_chain_col];
}
private:
const std::string _model_name, _chain_name;
int _model_col, _chain_col;
};
static std::unique_ptr<std::set<int>>
get_models(const gemmi::cif::Document &doc)
{
auto models = std::make_unique<std::set<int>>();
for (auto block : doc.blocks) {
for (auto site : block.find("_atom_site.", {"pdbx_PDB_model_num"})) {
models->insert(gemmi::cif::as_int(site[0]));
}
}
return models;
}
static std::unique_ptr<std::set<std::string>>
get_chains(const gemmi::cif::Document &doc)
{
auto chains = std::make_unique<std::set<std::string>>();
for (auto block : doc.blocks) {
for (auto site : block.find("_atom_site.", {"auth_asym_id"})) {
chains->insert(site[0]);
}
}
return chains;
}
static std::unique_ptr<std::set<std::string>>
get_chains(const gemmi::Model &model)
{
auto chains = std::make_unique<std::set<std::string>>();
for (auto &chain : model.chains) {
chains->insert(chain.name);
}
return chains;
}
static const auto atom_site_columns = std::vector<std::string>({
"group_PDB",
"auth_asym_id",
"auth_seq_id",
"pdbx_PDB_ins_code",
"auth_comp_id",
"auth_atom_id",
"label_alt_id",
"type_symbol",
"Cartn_x",
"Cartn_y",
"Cartn_z",
"pdbx_PDB_model_num",
});
static freesasa_cif_atom
freesasa_atom_from_site(const gemmi::cif::Table::Row &site)
{
std::unique_ptr<std::string> auth_atom_id;
// remove quotation marks if necessary
if (site[5][0] == '"') {
auth_atom_id = std::make_unique<std::string>(site[5].substr(1, site[5].size() - 2));
}
return {
.group_PDB = site[0].c_str(),
.auth_asym_id = site[1][0],
.auth_seq_id = site[2].c_str(),
.pdbx_PDB_ins_code = site[3].c_str(),
.auth_comp_id = site[4].c_str(),
.auth_atom_id = auth_atom_id ? std::move(*auth_atom_id).c_str() : site[5].c_str(),
.label_alt_id = site[6].c_str(),
.type_symbol = site[7].c_str(),
.Cartn_x = atof(site[8].c_str()),
.Cartn_y = atof(site[9].c_str()),
.Cartn_z = atof(site[10].c_str())};
}
template <typename T>
static freesasa_structure *
freesasa_structure_from_pred(const gemmi::cif::Document &doc,
const T &discriminator,
const freesasa_classifier *classifier,
int structure_options)
{
freesasa_structure *structure = freesasa_structure_new();
std::string auth_atom_id;
for (auto block : doc.blocks) {
for (auto site : block.find("_atom_site.", atom_site_columns)) {
if (site[0] != "ATOM" && !(structure_options & FREESASA_INCLUDE_HETATM)) {
continue;
}
if (discriminator(site)) continue;
freesasa_cif_atom atom = freesasa_atom_from_site(site);
if (!(structure_options & FREESASA_INCLUDE_HYDROGEN) && std::string(atom.type_symbol) == "H") {
continue;
}
// Pick the first alternative conformation for an atom
auto currentAltId = site[6][0];
if (currentAltId != '.' && currentAltId != 'A') {
continue;
}
freesasa_structure_add_cif_atom(structure, &atom, classifier, structure_options);
}
}
return structure;
}
freesasa_structure *
freesasa_structure_from_cif(std::FILE *input,
const freesasa_classifier *classifier,
int structure_options)
{
const auto doc = gemmi::cif::read_cstream(input, 8192, "cif-input");
const auto models = get_models(doc);
std::unique_ptr<const ModelSetDiscriminator> discriminator;
if (structure_options & FREESASA_JOIN_MODELS) {
discriminator = std::make_unique<const ModelSetDiscriminator>(std::move(*models));
} else {
auto firstModel = models->begin();
auto singleModel = std::set<int>{*firstModel};
discriminator = std::make_unique<const ModelSetDiscriminator>(singleModel);
}
return freesasa_structure_from_pred(doc, *discriminator, classifier, structure_options);
}
freesasa_structure *
freesasa_structure_from_model(const gemmi::cif::Document &doc,
const std::string &model_name,
const freesasa_classifier *classifier,
int structure_options)
{
const ModelDiscriminator discriminator(model_name);
return freesasa_structure_from_pred(doc, discriminator, classifier, structure_options);
freesasa_structure *structure = freesasa_structure_new();
}
freesasa_structure *
freesasa_structure_from_chain(const gemmi::cif::Document doc,
const std::string &model_name,
const std::string &chain_name,
const freesasa_classifier *classifier,
int structure_options)
{
const ChainDiscriminator discriminator(model_name, chain_name);
return freesasa_structure_from_pred(doc, discriminator, classifier, structure_options);
}
std::vector<freesasa_structure *>
freesasa_cif_structure_array(std::FILE *input,
int *n,
const freesasa_classifier *classifier,
int options)
{
int n_models = 0, n_chains = 0;
std::vector<freesasa_structure *> ss;
const auto doc = gemmi::cif::read_cstream(input, 8192, "cif-input");
gemmi::Structure gemmi_struct = gemmi::make_structure_from_block(doc.blocks[0]);
const auto models = gemmi_struct.models;
n_models = models.size();
/* only keep first model if option not provided */
if (!(options & FREESASA_SEPARATE_MODELS)) n_models = 1;
/* for each model read chains if requested */
if (options & FREESASA_SEPARATE_CHAINS) {
for (int i = 0; i < n_models; ++i) {
auto chain_names = get_chains(models[i]);
int n_new_chains = chain_names->size();
n_chains += n_new_chains;
if (n_new_chains == 0) {
freesasa_warn("in %s(): no chains found (in model %s)", __func__, models[i].name.c_str());
continue;
}
ss.reserve(n_new_chains);
for (auto &chain_name : *chain_names) {
ss.emplace_back(
freesasa_structure_from_chain(doc, models[i].name, chain_name, classifier, options));
freesasa_structure_set_model(ss.back(), i + 1);
}
}
if (n_chains == 0) freesasa_fail("In %s(): No chains in any model in protein: %s.", __func__, gemmi_struct.name.c_str());
*n = n_chains;
} else {
ss.reserve(n_models);
for (int i = 0; i < n_models; ++i) {
ss.emplace_back(
freesasa_structure_from_model(doc, models[i].name, classifier, options));
freesasa_structure_set_model(ss.back(), i + 1);
}
*n = n_models;
}
return ss;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team 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.
*******************************************************************************/
//==============================================================================
// Main
//==============================================================================
#include "checkforupdateswindow.h"
#include "cliutils.h"
#include "coresettings.h"
#include "guiutils.h"
#include "mainwindow.h"
#include "settings.h"
#include "splashscreenwindow.h"
//==============================================================================
#include <QDir>
#include <QLocale>
#include <QProcess>
#include <QSettings>
#include <QVariant>
#ifdef Q_OS_WIN
#include <QWebSettings>
#endif
//==============================================================================
#include <QtSingleApplication>
//==============================================================================
#include <stdlib.h>
//==============================================================================
int main(int pArgC, char *pArgV[])
{
// Remove all 'global' instances, in case OpenCOR previously crashed or
// something (and therefore didn't remove all of them before quitting)
OpenCOR::removeGlobalInstances();
// Determine whether we should try the CLI version of OpenCOR:
// - Windows: we never try the CLI version of OpenCOR. We go straight for
// its GUI version.
// - Linux: we always try the CLI version of OpenCOR and then go for its
// GUI version, if needed.
// - OS X: we try the CLI version of OpenCOR unless the user double clicks
// on the OpenCOR bundle or opens it from the command line by
// entering something like:
// open OpenCOR.app
// in which case we go for its GUI version.
// Note #1: on Windows, we have two binaries (.com and .exe that are for the
// CLI and GUI versions of OpenCOR, respectively). This means that
// when a console window is open, to enter something like:
// C:\>OpenCOR
// will effectively call OpenCOR.com. From there, should there be
// no argument that requires CLI treatment, then the GUI version of
// OpenCOR will be run. This is, unfortunately, the only way to
// have OpenCOR to behave as both a CLI and a GUI application on
// Windows, hence the [OpenCOR]/windows/main.cpp file, which is
// used to generate the CLI version of OpenCOR...
// Note #2: on OS X, if we were to try to open the OpenCOR bundle from the
// command line, then we would get an error message similar to:
// LSOpenURLsWithRole() failed with error -10810 for the file [SomePath]/OpenCOR.app.
// Fortunately, when double clicking on the OpenCOR bundle or
// opening it from the command line, a special argument in the form
// of -psn_0_1234567 is passed to OpenCOR, so we can use that to
// determine whether we need to force OpenCOR to be run in GUI mode
// or whether we first try the CLI version of OpenCOR, and then the
// GUI version if needed...
#if defined(Q_OS_WIN)
bool tryCliVersion = false;
#elif defined(Q_OS_LINUX)
bool tryCliVersion = true;
#elif defined(Q_OS_MAC)
bool tryCliVersion = (pArgC == 1) || memcmp(pArgV[1], "-psn_", 5);
#else
#error Unsupported platform
#endif
// Run the CLI version of OpenCOR, if possible/needed
if (tryCliVersion) {
// Initialise the plugins path
OpenCOR::initPluginsPath(pArgV[0]);
// Create and initialise the CLI version of OpenCOR
QCoreApplication *cliApp = new QCoreApplication(pArgC, pArgV);
OpenCOR::initApplication(cliApp);
// Try to run the CLI version of OpenCOR
int res;
bool runCliApplication = OpenCOR::cliApplication(cliApp, &res);
delete cliApp;
if (runCliApplication) {
// OpenCOR was run as a CLI application, so remove all our global
// instances and leave
OpenCOR::removeGlobalInstances();
return res;
}
// Note: at this stage, we tried the CLI version of OpenCOR, but in the
// end we need to go for its GUI version, so start over but with
// the GUI version of OpenCOR this time...
}
// Make sure that we always use indirect rendering on Linux
// Note: indeed, depending on which plugins are selected, OpenCOR may need
// LLVM. If that's the case, and in case the user's video card uses a
// driver that relies on LLVM (e.g. Gallium3D and Mesa 3D), then there
// may be a conflict between the version of LLVM used by OpenCOR and
// the one used by the video card. One way to address this issue is by
// using indirect rendering...
#ifdef Q_OS_LINUX
setenv("LIBGL_ALWAYS_INDIRECT", "1", 1);
#endif
// Initialise the plugins path
OpenCOR::initPluginsPath(pArgV[0]);
// Create and initialise the GUI version of OpenCOR
// Note: if we tried the CLI version of OpenCOR before, then it won't have
// done anything, so no need to re-remove all 'global' instances...
SharedTools::QtSingleApplication *guiApp = new SharedTools::QtSingleApplication(QFileInfo(pArgV[0]).baseName(),
pArgC, pArgV);
QString appDate = QString();
OpenCOR::initApplication(guiApp, &appDate);
// Check whether we want to check for new versions at startup
QSettings settings(OpenCOR::SettingsOrganization, OpenCOR::SettingsApplication);
#ifndef QT_DEBUG
settings.beginGroup("CheckForUpdatesWindow");
bool checkForUpdatesAtStartup = settings.value(OpenCOR::SettingsCheckForUpdatesAtStartup, true).toBool();
bool includeSnapshots = settings.value(OpenCOR::SettingsIncludeSnapshots, false).toBool();
settings.endGroup();
#endif
// Check whether a new version of OpenCOR is available
#ifndef QT_DEBUG
if (checkForUpdatesAtStartup) {
OpenCOR::CheckForUpdatesEngine *checkForUpdatesEngine = new OpenCOR::CheckForUpdatesEngine(appDate);
checkForUpdatesEngine->check();
if ( ( includeSnapshots && checkForUpdatesEngine->hasNewerVersion())
|| (!includeSnapshots && checkForUpdatesEngine->hasNewerOfficialVersion())) {
// Retrieve the language to be used to show the check for updates
// window
const QString systemLocale = QLocale::system().name().left(2);
QString locale = settings.value(OpenCOR::SettingsLocale, QString()).toString();
if (locale.isEmpty())
locale = systemLocale;
QLocale::setDefault(QLocale(locale));
QTranslator qtTranslator;
QTranslator appTranslator;
qtTranslator.load(":qt_"+locale);
qApp->installTranslator(&qtTranslator);
appTranslator.load(":app_"+locale);
qApp->installTranslator(&appTranslator);
// Show the check for updates window
// Note: checkForUpdatesEngine gets deleted by
// checkForUpdatesWindow...
OpenCOR::CheckForUpdatesWindow checkForUpdatesWindow(checkForUpdatesEngine);
settings.beginGroup(checkForUpdatesWindow.objectName());
checkForUpdatesWindow.loadSettings(&settings);
settings.endGroup();
checkForUpdatesWindow.exec();
settings.beginGroup(checkForUpdatesWindow.objectName());
checkForUpdatesWindow.saveSettings(&settings);
settings.endGroup();
} else {
delete checkForUpdatesEngine;
}
}
#endif
// Initialise our colours by 'updating' them
OpenCOR::updateColors();
// Create and show our splash screen, if we are not in debug mode
#ifndef QT_DEBUG
OpenCOR::SplashScreenWindow *splashScreen = new OpenCOR::SplashScreenWindow();
splashScreen->show();
guiApp->processEvents();
// Note: this ensures that our splash screen is immediately visible...
#endif
// Send a message (containing the arguments that were passed to this
// instance of OpenCOR minus the first one since it corresponds to the full
// path to our executable, which we are not interested in) to our 'official'
// instance of OpenCOR, should there be one. If there is no none, then just
// carry on as normal, otherwise exit since we want only one instance of
// OpenCOR at any given time
QStringList appArguments = guiApp->arguments();
appArguments.removeFirst();
QString arguments = appArguments.join("|");
if (guiApp->isRunning()) {
guiApp->sendMessage(arguments);
delete guiApp;
return 0;
}
// Create our main window
OpenCOR::MainWindow *win = new OpenCOR::MainWindow(guiApp, appDate);
// Keep track of our main window (required by QtSingleApplication so that it
// can do what it's supposed to be doing)
guiApp->setActivationWindow(win);
// Handle our arguments
win->handleArguments(arguments);
// Show our main window
win->show();
// By default, we can and should execute our application
bool canExecuteAplication = true;
// Close and delete our splash screen once our main window is visible, if we
// are not in debug mode
#ifndef QT_DEBUG
splashScreen->closeAndDeleteAfter(win);
// Make sure that our main window is in the foreground, unless the user
// decided to close our main window while we were showing our splash screen
// Note: indeed, on Linux, to show our splash screen may result in our main
// window being shown in the background...
if (!win->shuttingDown())
win->showSelf();
else
canExecuteAplication = false;
#endif
// Execute our application, if possible
int res;
if (canExecuteAplication)
res = guiApp->exec();
else
res = 0;
// Keep track of our application file and directory paths (in case we need
// to restart OpenCOR)
QString appFilePath = guiApp->applicationFilePath();
QString appDirPath = guiApp->applicationDirPath();
// Delete our main window
delete win;
// If we use QtWebKit, and QWebPage in particular, then leak messages will
// get generated on Windows when leaving OpenCOR. This is because an object
// cache is shared between all QWebPage instances. So to destroy a QWebPage
// instance won't clear the cache, hence the leak messages. However, these
// messages are 'only' warnings, so we can safely live with them. Still, it
// doesn't look 'good', so we clear the memory caches, thus avoiding those
// leak messages...
// Note: the below must absolutely be done after calling guiApp->exec() and
// before deleting guiApp...
#ifdef Q_OS_WIN
QWebSettings::clearMemoryCaches();
#endif
// Remove all 'global' instances that were created and used during this
// session
OpenCOR::removeGlobalInstances();
// Delete our application
delete guiApp;
// We are done with the execution of our application, so now the question is
// whether we need to restart
// Note: we do this here rather than 'within' the GUI because once we have
// launched a new instance of OpenCOR, we want this instance of
// OpenCOR to finish as soon as possible, which will be the case here
// since all that remains to be done is to return the result of the
// execution of our application...
if ((res == OpenCOR::CleanRestart) || (res == OpenCOR::NormalRestart)) {
// We want to restart, so the question is whether we want a normal
// restart or a clean one
if (res == OpenCOR::CleanRestart)
// We want a clean restart, so clear all the user settings (indeed,
// this will ensure that the various windows are, for instance,
// properly reset with regards to their dimensions)
settings.clear();
// Restart OpenCOR, but without providing any of the arguments that were
// originally passed to us since we want to reset everything
QProcess::startDetached(appFilePath, QStringList(), appDirPath);
}
// We are done running the GUI version of OpenCOR, so leave
return res;
}
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Qt54: some work towards using Qt WebEngine instead of Qt WebKit (#514) [ci skip].<commit_after>/*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team 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.
*******************************************************************************/
//==============================================================================
// Main
//==============================================================================
#include "checkforupdateswindow.h"
#include "cliutils.h"
#include "coresettings.h"
#include "guiutils.h"
#include "mainwindow.h"
#include "settings.h"
#include "splashscreenwindow.h"
//==============================================================================
#include <QDir>
#include <QLocale>
#include <QProcess>
#include <QSettings>
#include <QVariant>
//==============================================================================
#include <QtSingleApplication>
//==============================================================================
#include <stdlib.h>
//==============================================================================
int main(int pArgC, char *pArgV[])
{
// Remove all 'global' instances, in case OpenCOR previously crashed or
// something (and therefore didn't remove all of them before quitting)
OpenCOR::removeGlobalInstances();
// Determine whether we should try the CLI version of OpenCOR:
// - Windows: we never try the CLI version of OpenCOR. We go straight for
// its GUI version.
// - Linux: we always try the CLI version of OpenCOR and then go for its
// GUI version, if needed.
// - OS X: we try the CLI version of OpenCOR unless the user double clicks
// on the OpenCOR bundle or opens it from the command line by
// entering something like:
// open OpenCOR.app
// in which case we go for its GUI version.
// Note #1: on Windows, we have two binaries (.com and .exe that are for the
// CLI and GUI versions of OpenCOR, respectively). This means that
// when a console window is open, to enter something like:
// C:\>OpenCOR
// will effectively call OpenCOR.com. From there, should there be
// no argument that requires CLI treatment, then the GUI version of
// OpenCOR will be run. This is, unfortunately, the only way to
// have OpenCOR to behave as both a CLI and a GUI application on
// Windows, hence the [OpenCOR]/windows/main.cpp file, which is
// used to generate the CLI version of OpenCOR...
// Note #2: on OS X, if we were to try to open the OpenCOR bundle from the
// command line, then we would get an error message similar to:
// LSOpenURLsWithRole() failed with error -10810 for the file [SomePath]/OpenCOR.app.
// Fortunately, when double clicking on the OpenCOR bundle or
// opening it from the command line, a special argument in the form
// of -psn_0_1234567 is passed to OpenCOR, so we can use that to
// determine whether we need to force OpenCOR to be run in GUI mode
// or whether we first try the CLI version of OpenCOR, and then the
// GUI version if needed...
#if defined(Q_OS_WIN)
bool tryCliVersion = false;
#elif defined(Q_OS_LINUX)
bool tryCliVersion = true;
#elif defined(Q_OS_MAC)
bool tryCliVersion = (pArgC == 1) || memcmp(pArgV[1], "-psn_", 5);
#else
#error Unsupported platform
#endif
// Run the CLI version of OpenCOR, if possible/needed
if (tryCliVersion) {
// Initialise the plugins path
OpenCOR::initPluginsPath(pArgV[0]);
// Create and initialise the CLI version of OpenCOR
QCoreApplication *cliApp = new QCoreApplication(pArgC, pArgV);
OpenCOR::initApplication(cliApp);
// Try to run the CLI version of OpenCOR
int res;
bool runCliApplication = OpenCOR::cliApplication(cliApp, &res);
delete cliApp;
if (runCliApplication) {
// OpenCOR was run as a CLI application, so remove all our global
// instances and leave
OpenCOR::removeGlobalInstances();
return res;
}
// Note: at this stage, we tried the CLI version of OpenCOR, but in the
// end we need to go for its GUI version, so start over but with
// the GUI version of OpenCOR this time...
}
// Make sure that we always use indirect rendering on Linux
// Note: indeed, depending on which plugins are selected, OpenCOR may need
// LLVM. If that's the case, and in case the user's video card uses a
// driver that relies on LLVM (e.g. Gallium3D and Mesa 3D), then there
// may be a conflict between the version of LLVM used by OpenCOR and
// the one used by the video card. One way to address this issue is by
// using indirect rendering...
#ifdef Q_OS_LINUX
setenv("LIBGL_ALWAYS_INDIRECT", "1", 1);
#endif
// Initialise the plugins path
OpenCOR::initPluginsPath(pArgV[0]);
// Create and initialise the GUI version of OpenCOR
// Note: if we tried the CLI version of OpenCOR before, then it won't have
// done anything, so no need to re-remove all 'global' instances...
SharedTools::QtSingleApplication *guiApp = new SharedTools::QtSingleApplication(QFileInfo(pArgV[0]).baseName(),
pArgC, pArgV);
QString appDate = QString();
OpenCOR::initApplication(guiApp, &appDate);
// Check whether we want to check for new versions at startup
QSettings settings(OpenCOR::SettingsOrganization, OpenCOR::SettingsApplication);
#ifndef QT_DEBUG
settings.beginGroup("CheckForUpdatesWindow");
bool checkForUpdatesAtStartup = settings.value(OpenCOR::SettingsCheckForUpdatesAtStartup, true).toBool();
bool includeSnapshots = settings.value(OpenCOR::SettingsIncludeSnapshots, false).toBool();
settings.endGroup();
#endif
// Check whether a new version of OpenCOR is available
#ifndef QT_DEBUG
if (checkForUpdatesAtStartup) {
OpenCOR::CheckForUpdatesEngine *checkForUpdatesEngine = new OpenCOR::CheckForUpdatesEngine(appDate);
checkForUpdatesEngine->check();
if ( ( includeSnapshots && checkForUpdatesEngine->hasNewerVersion())
|| (!includeSnapshots && checkForUpdatesEngine->hasNewerOfficialVersion())) {
// Retrieve the language to be used to show the check for updates
// window
const QString systemLocale = QLocale::system().name().left(2);
QString locale = settings.value(OpenCOR::SettingsLocale, QString()).toString();
if (locale.isEmpty())
locale = systemLocale;
QLocale::setDefault(QLocale(locale));
QTranslator qtTranslator;
QTranslator appTranslator;
qtTranslator.load(":qt_"+locale);
qApp->installTranslator(&qtTranslator);
appTranslator.load(":app_"+locale);
qApp->installTranslator(&appTranslator);
// Show the check for updates window
// Note: checkForUpdatesEngine gets deleted by
// checkForUpdatesWindow...
OpenCOR::CheckForUpdatesWindow checkForUpdatesWindow(checkForUpdatesEngine);
settings.beginGroup(checkForUpdatesWindow.objectName());
checkForUpdatesWindow.loadSettings(&settings);
settings.endGroup();
checkForUpdatesWindow.exec();
settings.beginGroup(checkForUpdatesWindow.objectName());
checkForUpdatesWindow.saveSettings(&settings);
settings.endGroup();
} else {
delete checkForUpdatesEngine;
}
}
#endif
// Initialise our colours by 'updating' them
OpenCOR::updateColors();
// Create and show our splash screen, if we are not in debug mode
#ifndef QT_DEBUG
OpenCOR::SplashScreenWindow *splashScreen = new OpenCOR::SplashScreenWindow();
splashScreen->show();
guiApp->processEvents();
// Note: this ensures that our splash screen is immediately visible...
#endif
// Send a message (containing the arguments that were passed to this
// instance of OpenCOR minus the first one since it corresponds to the full
// path to our executable, which we are not interested in) to our 'official'
// instance of OpenCOR, should there be one. If there is no none, then just
// carry on as normal, otherwise exit since we want only one instance of
// OpenCOR at any given time
QStringList appArguments = guiApp->arguments();
appArguments.removeFirst();
QString arguments = appArguments.join("|");
if (guiApp->isRunning()) {
guiApp->sendMessage(arguments);
delete guiApp;
return 0;
}
// Create our main window
OpenCOR::MainWindow *win = new OpenCOR::MainWindow(guiApp, appDate);
// Keep track of our main window (required by QtSingleApplication so that it
// can do what it's supposed to be doing)
guiApp->setActivationWindow(win);
// Handle our arguments
win->handleArguments(arguments);
// Show our main window
win->show();
// By default, we can and should execute our application
bool canExecuteAplication = true;
// Close and delete our splash screen once our main window is visible, if we
// are not in debug mode
#ifndef QT_DEBUG
splashScreen->closeAndDeleteAfter(win);
// Make sure that our main window is in the foreground, unless the user
// decided to close our main window while we were showing our splash screen
// Note: indeed, on Linux, to show our splash screen may result in our main
// window being shown in the background...
if (!win->shuttingDown())
win->showSelf();
else
canExecuteAplication = false;
#endif
// Execute our application, if possible
int res;
if (canExecuteAplication)
res = guiApp->exec();
else
res = 0;
// Keep track of our application file and directory paths (in case we need
// to restart OpenCOR)
QString appFilePath = guiApp->applicationFilePath();
QString appDirPath = guiApp->applicationDirPath();
// Delete our main window
delete win;
// Remove all 'global' instances that were created and used during this
// session
OpenCOR::removeGlobalInstances();
// Delete our application
delete guiApp;
// We are done with the execution of our application, so now the question is
// whether we need to restart
// Note: we do this here rather than 'within' the GUI because once we have
// launched a new instance of OpenCOR, we want this instance of
// OpenCOR to finish as soon as possible, which will be the case here
// since all that remains to be done is to return the result of the
// execution of our application...
if ((res == OpenCOR::CleanRestart) || (res == OpenCOR::NormalRestart)) {
// We want to restart, so the question is whether we want a normal
// restart or a clean one
if (res == OpenCOR::CleanRestart)
// We want a clean restart, so clear all the user settings (indeed,
// this will ensure that the various windows are, for instance,
// properly reset with regards to their dimensions)
settings.clear();
// Restart OpenCOR, but without providing any of the arguments that were
// originally passed to us since we want to reset everything
QProcess::startDetached(appFilePath, QStringList(), appDirPath);
}
// We are done running the GUI version of OpenCOR, so leave
return res;
}
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>#include "../include/cxx.h"
#include <cstring>
#include <exception>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <vector>
extern "C" {
const char *cxxbridge05$cxx_string$data(const std::string &s) noexcept {
return s.data();
}
size_t cxxbridge05$cxx_string$length(const std::string &s) noexcept {
return s.length();
}
// rust::String
void cxxbridge05$string$new(rust::String *self) noexcept;
void cxxbridge05$string$clone(rust::String *self,
const rust::String &other) noexcept;
bool cxxbridge05$string$from(rust::String *self, const char *ptr,
size_t len) noexcept;
void cxxbridge05$string$drop(rust::String *self) noexcept;
const char *cxxbridge05$string$ptr(const rust::String *self) noexcept;
size_t cxxbridge05$string$len(const rust::String *self) noexcept;
// rust::Str
bool cxxbridge05$str$valid(const char *ptr, size_t len) noexcept;
} // extern "C"
namespace rust {
inline namespace cxxbridge05 {
template <typename Exception>
void panic [[noreturn]] (const char *msg) {
#if defined(RUST_CXX_NO_EXCEPTIONS)
std::cerr << "Error: " << msg << ". Aborting." << std::endl;
std::terminate();
#else
throw Exception(msg);
#endif
}
template void panic<std::out_of_range>[[noreturn]] (const char *msg);
String::String() noexcept { cxxbridge05$string$new(this); }
String::String(const String &other) noexcept {
cxxbridge05$string$clone(this, other);
}
String::String(String &&other) noexcept {
this->repr = other.repr;
cxxbridge05$string$new(&other);
}
String::~String() noexcept { cxxbridge05$string$drop(this); }
String::String(const std::string &s) : String(s.data(), s.length()) {}
String::String(const char *s) : String(s, std::strlen(s)) {}
String::String(const char *s, size_t len) {
if (!cxxbridge05$string$from(this, s, len)) {
panic<std::invalid_argument>("data for rust::String is not utf-8");
}
}
String &String::operator=(const String &other) noexcept {
if (this != &other) {
cxxbridge05$string$drop(this);
cxxbridge05$string$clone(this, other);
}
return *this;
}
String &String::operator=(String &&other) noexcept {
if (this != &other) {
cxxbridge05$string$drop(this);
this->repr = other.repr;
cxxbridge05$string$new(&other);
}
return *this;
}
String::operator std::string() const {
return std::string(this->data(), this->size());
}
const char *String::data() const noexcept {
return cxxbridge05$string$ptr(this);
}
size_t String::size() const noexcept { return cxxbridge05$string$len(this); }
size_t String::length() const noexcept { return cxxbridge05$string$len(this); }
String::String(unsafe_bitcopy_t, const String &bits) noexcept
: repr(bits.repr) {}
std::ostream &operator<<(std::ostream &os, const String &s) {
os.write(s.data(), s.size());
return os;
}
Str::Str() noexcept : repr(Repr{reinterpret_cast<const char *>(this), 0}) {}
Str::Str(const Str &) noexcept = default;
Str::Str(const std::string &s) : Str(s.data(), s.length()) {}
Str::Str(const char *s) : Str(s, std::strlen(s)) {}
Str::Str(const char *s, size_t len) : repr(Repr{s, len}) {
if (!cxxbridge05$str$valid(this->repr.ptr, this->repr.len)) {
panic<std::invalid_argument>("data for rust::Str is not utf-8");
}
}
Str &Str::operator=(Str other) noexcept {
this->repr = other.repr;
return *this;
}
Str::operator std::string() const {
return std::string(this->data(), this->size());
}
const char *Str::data() const noexcept { return this->repr.ptr; }
size_t Str::size() const noexcept { return this->repr.len; }
size_t Str::length() const noexcept { return this->repr.len; }
Str::Str(Repr repr_) noexcept : repr(repr_) {}
Str::operator Repr() noexcept { return this->repr; }
std::ostream &operator<<(std::ostream &os, const Str &s) {
os.write(s.data(), s.size());
return os;
}
extern "C" {
const char *cxxbridge05$error(const char *ptr, size_t len) {
char *copy = new char[len];
strncpy(copy, ptr, len);
return copy;
}
} // extern "C"
Error::Error(Str::Repr msg) noexcept : msg(msg) {}
Error::Error(const Error &other) {
this->msg.ptr = cxxbridge05$error(other.msg.ptr, other.msg.len);
this->msg.len = other.msg.len;
}
Error::Error(Error &&other) noexcept {
delete[] this->msg.ptr;
this->msg = other.msg;
other.msg.ptr = nullptr;
other.msg.len = 0;
}
Error::~Error() noexcept { delete[] this->msg.ptr; }
const char *Error::what() const noexcept { return this->msg.ptr; }
} // namespace cxxbridge05
} // namespace rust
extern "C" {
void cxxbridge05$unique_ptr$std$string$null(
std::unique_ptr<std::string> *ptr) noexcept {
new (ptr) std::unique_ptr<std::string>();
}
void cxxbridge05$unique_ptr$std$string$raw(std::unique_ptr<std::string> *ptr,
std::string *raw) noexcept {
new (ptr) std::unique_ptr<std::string>(raw);
}
const std::string *cxxbridge05$unique_ptr$std$string$get(
const std::unique_ptr<std::string> &ptr) noexcept {
return ptr.get();
}
std::string *cxxbridge05$unique_ptr$std$string$release(
std::unique_ptr<std::string> &ptr) noexcept {
return ptr.release();
}
void cxxbridge05$unique_ptr$std$string$drop(
std::unique_ptr<std::string> *ptr) noexcept {
ptr->~unique_ptr();
}
} // extern "C"
#define STD_VECTOR_OPS(RUST_TYPE, CXX_TYPE) \
size_t cxxbridge05$std$vector$##RUST_TYPE##$size( \
const std::vector<CXX_TYPE> &s) noexcept { \
return s.size(); \
} \
const CXX_TYPE *cxxbridge05$std$vector$##RUST_TYPE##$get_unchecked( \
const std::vector<CXX_TYPE> &s, size_t pos) noexcept { \
return &s[pos]; \
} \
void cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$null( \
std::unique_ptr<std::vector<CXX_TYPE>> *ptr) noexcept { \
new (ptr) std::unique_ptr<std::vector<CXX_TYPE>>(); \
} \
void cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$raw( \
std::unique_ptr<std::vector<CXX_TYPE>> *ptr, \
std::vector<CXX_TYPE> *raw) noexcept { \
new (ptr) std::unique_ptr<std::vector<CXX_TYPE>>(raw); \
} \
const std::vector<CXX_TYPE> \
*cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$get( \
const std::unique_ptr<std::vector<CXX_TYPE>> &ptr) noexcept { \
return ptr.get(); \
} \
std::vector<CXX_TYPE> \
*cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$release( \
std::unique_ptr<std::vector<CXX_TYPE>> &ptr) noexcept { \
return ptr.release(); \
} \
void cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$drop( \
std::unique_ptr<std::vector<CXX_TYPE>> *ptr) noexcept { \
ptr->~unique_ptr(); \
}
#define RUST_VEC_EXTERNS(RUST_TYPE, CXX_TYPE) \
void cxxbridge05$rust_vec$##RUST_TYPE##$new( \
rust::Vec<CXX_TYPE> *ptr) noexcept; \
void cxxbridge05$rust_vec$##RUST_TYPE##$drop( \
rust::Vec<CXX_TYPE> *ptr) noexcept; \
size_t cxxbridge05$rust_vec$##RUST_TYPE##$len( \
const rust::Vec<CXX_TYPE> *ptr) noexcept; \
const CXX_TYPE *cxxbridge05$rust_vec$##RUST_TYPE##$data( \
const rust::Vec<CXX_TYPE> *ptr) noexcept; \
size_t cxxbridge05$rust_vec$##RUST_TYPE##$stride() noexcept;
#define RUST_VEC_OPS(RUST_TYPE, CXX_TYPE) \
template <> \
Vec<CXX_TYPE>::Vec() noexcept { \
cxxbridge05$rust_vec$##RUST_TYPE##$new(this); \
} \
template <> \
void Vec<CXX_TYPE>::drop() noexcept { \
return cxxbridge05$rust_vec$##RUST_TYPE##$drop(this); \
} \
template <> \
size_t Vec<CXX_TYPE>::size() const noexcept { \
return cxxbridge05$rust_vec$##RUST_TYPE##$len(this); \
} \
template <> \
const CXX_TYPE *Vec<CXX_TYPE>::data() const noexcept { \
return cxxbridge05$rust_vec$##RUST_TYPE##$data(this); \
} \
template <> \
size_t Vec<CXX_TYPE>::stride() noexcept { \
return cxxbridge05$rust_vec$##RUST_TYPE##$stride(); \
}
// Usize and isize are the same type as one of the below.
#define FOR_EACH_NUMERIC(MACRO) \
MACRO(u8, uint8_t) \
MACRO(u16, uint16_t) \
MACRO(u32, uint32_t) \
MACRO(u64, uint64_t) \
MACRO(i8, int8_t) \
MACRO(i16, int16_t) \
MACRO(i32, int32_t) \
MACRO(i64, int64_t) \
MACRO(f32, float) \
MACRO(f64, double)
#define FOR_EACH_STD_VECTOR(MACRO) \
FOR_EACH_NUMERIC(MACRO) \
MACRO(usize, size_t) \
MACRO(isize, rust::isize) \
MACRO(string, std::string)
#define FOR_EACH_RUST_VEC(MACRO) \
FOR_EACH_NUMERIC(MACRO) \
MACRO(bool, bool) \
MACRO(string, rust::String)
extern "C" {
FOR_EACH_STD_VECTOR(STD_VECTOR_OPS)
FOR_EACH_RUST_VEC(RUST_VEC_EXTERNS)
} // extern "C"
namespace rust {
inline namespace cxxbridge05 {
FOR_EACH_RUST_VEC(RUST_VEC_OPS)
} // namespace cxxbridge05
} // namespace rust
<commit_msg>Match std::string's behavior on (nullptr, 0) construction<commit_after>#include "../include/cxx.h"
#include <cstring>
#include <exception>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <vector>
extern "C" {
const char *cxxbridge05$cxx_string$data(const std::string &s) noexcept {
return s.data();
}
size_t cxxbridge05$cxx_string$length(const std::string &s) noexcept {
return s.length();
}
// rust::String
void cxxbridge05$string$new(rust::String *self) noexcept;
void cxxbridge05$string$clone(rust::String *self,
const rust::String &other) noexcept;
bool cxxbridge05$string$from(rust::String *self, const char *ptr,
size_t len) noexcept;
void cxxbridge05$string$drop(rust::String *self) noexcept;
const char *cxxbridge05$string$ptr(const rust::String *self) noexcept;
size_t cxxbridge05$string$len(const rust::String *self) noexcept;
// rust::Str
bool cxxbridge05$str$valid(const char *ptr, size_t len) noexcept;
} // extern "C"
namespace rust {
inline namespace cxxbridge05 {
template <typename Exception>
void panic [[noreturn]] (const char *msg) {
#if defined(RUST_CXX_NO_EXCEPTIONS)
std::cerr << "Error: " << msg << ". Aborting." << std::endl;
std::terminate();
#else
throw Exception(msg);
#endif
}
template void panic<std::out_of_range>[[noreturn]] (const char *msg);
String::String() noexcept { cxxbridge05$string$new(this); }
String::String(const String &other) noexcept {
cxxbridge05$string$clone(this, other);
}
String::String(String &&other) noexcept {
this->repr = other.repr;
cxxbridge05$string$new(&other);
}
String::~String() noexcept { cxxbridge05$string$drop(this); }
String::String(const std::string &s) {
if (!cxxbridge05$string$from(this, s.data(), s.length())) {
panic<std::invalid_argument>("data for rust::String is not utf-8");
}
}
String::String(const char *s) {
if (!cxxbridge05$string$from(this, s, std::strlen(s))) {
panic<std::invalid_argument>("data for rust::String is not utf-8");
}
}
String::String(const char *s, size_t len) {
if (!cxxbridge05$string$from(
this,
s == nullptr && len == 0 ? reinterpret_cast<const char *>(1) : s,
len)) {
panic<std::invalid_argument>("data for rust::String is not utf-8");
}
}
String &String::operator=(const String &other) noexcept {
if (this != &other) {
cxxbridge05$string$drop(this);
cxxbridge05$string$clone(this, other);
}
return *this;
}
String &String::operator=(String &&other) noexcept {
if (this != &other) {
cxxbridge05$string$drop(this);
this->repr = other.repr;
cxxbridge05$string$new(&other);
}
return *this;
}
String::operator std::string() const {
return std::string(this->data(), this->size());
}
const char *String::data() const noexcept {
return cxxbridge05$string$ptr(this);
}
size_t String::size() const noexcept { return cxxbridge05$string$len(this); }
size_t String::length() const noexcept { return cxxbridge05$string$len(this); }
String::String(unsafe_bitcopy_t, const String &bits) noexcept
: repr(bits.repr) {}
std::ostream &operator<<(std::ostream &os, const String &s) {
os.write(s.data(), s.size());
return os;
}
Str::Str() noexcept : repr(Repr{reinterpret_cast<const char *>(1), 0}) {}
Str::Str(const Str &) noexcept = default;
Str::Str(const std::string &s) : repr(Repr{s.data(), s.length()}) {
if (!cxxbridge05$str$valid(this->repr.ptr, this->repr.len)) {
panic<std::invalid_argument>("data for rust::Str is not utf-8");
}
}
Str::Str(const char *s) : repr(Repr{s, std::strlen(s)}) {
if (!cxxbridge05$str$valid(this->repr.ptr, this->repr.len)) {
panic<std::invalid_argument>("data for rust::Str is not utf-8");
}
}
Str::Str(const char *s, size_t len)
: repr(
Repr{s == nullptr && len == 0 ? reinterpret_cast<const char *>(1) : s,
len}) {
if (!cxxbridge05$str$valid(this->repr.ptr, this->repr.len)) {
panic<std::invalid_argument>("data for rust::Str is not utf-8");
}
}
Str &Str::operator=(Str other) noexcept {
this->repr = other.repr;
return *this;
}
Str::operator std::string() const {
return std::string(this->data(), this->size());
}
const char *Str::data() const noexcept { return this->repr.ptr; }
size_t Str::size() const noexcept { return this->repr.len; }
size_t Str::length() const noexcept { return this->repr.len; }
Str::Str(Repr repr_) noexcept : repr(repr_) {}
Str::operator Repr() noexcept { return this->repr; }
std::ostream &operator<<(std::ostream &os, const Str &s) {
os.write(s.data(), s.size());
return os;
}
extern "C" {
const char *cxxbridge05$error(const char *ptr, size_t len) {
char *copy = new char[len];
strncpy(copy, ptr, len);
return copy;
}
} // extern "C"
Error::Error(Str::Repr msg) noexcept : msg(msg) {}
Error::Error(const Error &other) {
this->msg.ptr = cxxbridge05$error(other.msg.ptr, other.msg.len);
this->msg.len = other.msg.len;
}
Error::Error(Error &&other) noexcept {
delete[] this->msg.ptr;
this->msg = other.msg;
other.msg.ptr = nullptr;
other.msg.len = 0;
}
Error::~Error() noexcept { delete[] this->msg.ptr; }
const char *Error::what() const noexcept { return this->msg.ptr; }
} // namespace cxxbridge05
} // namespace rust
extern "C" {
void cxxbridge05$unique_ptr$std$string$null(
std::unique_ptr<std::string> *ptr) noexcept {
new (ptr) std::unique_ptr<std::string>();
}
void cxxbridge05$unique_ptr$std$string$raw(std::unique_ptr<std::string> *ptr,
std::string *raw) noexcept {
new (ptr) std::unique_ptr<std::string>(raw);
}
const std::string *cxxbridge05$unique_ptr$std$string$get(
const std::unique_ptr<std::string> &ptr) noexcept {
return ptr.get();
}
std::string *cxxbridge05$unique_ptr$std$string$release(
std::unique_ptr<std::string> &ptr) noexcept {
return ptr.release();
}
void cxxbridge05$unique_ptr$std$string$drop(
std::unique_ptr<std::string> *ptr) noexcept {
ptr->~unique_ptr();
}
} // extern "C"
#define STD_VECTOR_OPS(RUST_TYPE, CXX_TYPE) \
size_t cxxbridge05$std$vector$##RUST_TYPE##$size( \
const std::vector<CXX_TYPE> &s) noexcept { \
return s.size(); \
} \
const CXX_TYPE *cxxbridge05$std$vector$##RUST_TYPE##$get_unchecked( \
const std::vector<CXX_TYPE> &s, size_t pos) noexcept { \
return &s[pos]; \
} \
void cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$null( \
std::unique_ptr<std::vector<CXX_TYPE>> *ptr) noexcept { \
new (ptr) std::unique_ptr<std::vector<CXX_TYPE>>(); \
} \
void cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$raw( \
std::unique_ptr<std::vector<CXX_TYPE>> *ptr, \
std::vector<CXX_TYPE> *raw) noexcept { \
new (ptr) std::unique_ptr<std::vector<CXX_TYPE>>(raw); \
} \
const std::vector<CXX_TYPE> \
*cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$get( \
const std::unique_ptr<std::vector<CXX_TYPE>> &ptr) noexcept { \
return ptr.get(); \
} \
std::vector<CXX_TYPE> \
*cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$release( \
std::unique_ptr<std::vector<CXX_TYPE>> &ptr) noexcept { \
return ptr.release(); \
} \
void cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$drop( \
std::unique_ptr<std::vector<CXX_TYPE>> *ptr) noexcept { \
ptr->~unique_ptr(); \
}
#define RUST_VEC_EXTERNS(RUST_TYPE, CXX_TYPE) \
void cxxbridge05$rust_vec$##RUST_TYPE##$new( \
rust::Vec<CXX_TYPE> *ptr) noexcept; \
void cxxbridge05$rust_vec$##RUST_TYPE##$drop( \
rust::Vec<CXX_TYPE> *ptr) noexcept; \
size_t cxxbridge05$rust_vec$##RUST_TYPE##$len( \
const rust::Vec<CXX_TYPE> *ptr) noexcept; \
const CXX_TYPE *cxxbridge05$rust_vec$##RUST_TYPE##$data( \
const rust::Vec<CXX_TYPE> *ptr) noexcept; \
size_t cxxbridge05$rust_vec$##RUST_TYPE##$stride() noexcept;
#define RUST_VEC_OPS(RUST_TYPE, CXX_TYPE) \
template <> \
Vec<CXX_TYPE>::Vec() noexcept { \
cxxbridge05$rust_vec$##RUST_TYPE##$new(this); \
} \
template <> \
void Vec<CXX_TYPE>::drop() noexcept { \
return cxxbridge05$rust_vec$##RUST_TYPE##$drop(this); \
} \
template <> \
size_t Vec<CXX_TYPE>::size() const noexcept { \
return cxxbridge05$rust_vec$##RUST_TYPE##$len(this); \
} \
template <> \
const CXX_TYPE *Vec<CXX_TYPE>::data() const noexcept { \
return cxxbridge05$rust_vec$##RUST_TYPE##$data(this); \
} \
template <> \
size_t Vec<CXX_TYPE>::stride() noexcept { \
return cxxbridge05$rust_vec$##RUST_TYPE##$stride(); \
}
// Usize and isize are the same type as one of the below.
#define FOR_EACH_NUMERIC(MACRO) \
MACRO(u8, uint8_t) \
MACRO(u16, uint16_t) \
MACRO(u32, uint32_t) \
MACRO(u64, uint64_t) \
MACRO(i8, int8_t) \
MACRO(i16, int16_t) \
MACRO(i32, int32_t) \
MACRO(i64, int64_t) \
MACRO(f32, float) \
MACRO(f64, double)
#define FOR_EACH_STD_VECTOR(MACRO) \
FOR_EACH_NUMERIC(MACRO) \
MACRO(usize, size_t) \
MACRO(isize, rust::isize) \
MACRO(string, std::string)
#define FOR_EACH_RUST_VEC(MACRO) \
FOR_EACH_NUMERIC(MACRO) \
MACRO(bool, bool) \
MACRO(string, rust::String)
extern "C" {
FOR_EACH_STD_VECTOR(STD_VECTOR_OPS)
FOR_EACH_RUST_VEC(RUST_VEC_EXTERNS)
} // extern "C"
namespace rust {
inline namespace cxxbridge05 {
FOR_EACH_RUST_VEC(RUST_VEC_OPS)
} // namespace cxxbridge05
} // namespace rust
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "db.h"
#include "addrman.h"
#include "hash.h"
#include "protocol.h"
#include "util.h"
#include "utilstrencodings.h"
#include <stdint.h>
#ifndef WIN32
#include <sys/stat.h>
#endif
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
#include <boost/version.hpp>
#include <openssl/rand.h>
using namespace std;
using namespace boost;
unsigned int nWalletDBUpdated;
//
// CDB
//
CDBEnv bitdb;
void CDBEnv::EnvShutdown()
{
if (!fDbEnvInit)
return;
fDbEnvInit = false;
int ret = dbenv.close(0);
if (ret != 0)
LogPrintf("CDBEnv::EnvShutdown : Error %d shutting down database environment: %s\n", ret, DbEnv::strerror(ret));
if (!fMockDb)
DbEnv(0).remove(path.string().c_str(), 0);
}
CDBEnv::CDBEnv() : dbenv(DB_CXX_NO_EXCEPTIONS)
{
fDbEnvInit = false;
fMockDb = false;
}
CDBEnv::~CDBEnv()
{
EnvShutdown();
}
void CDBEnv::Close()
{
EnvShutdown();
}
bool CDBEnv::Open(const boost::filesystem::path& pathIn)
{
if (fDbEnvInit)
return true;
boost::this_thread::interruption_point();
path = pathIn;
filesystem::path pathLogDir = path / "database";
TryCreateDirectory(pathLogDir);
filesystem::path pathErrorFile = path / "db.log";
LogPrintf("CDBEnv::Open : LogDir=%s ErrorFile=%s\n", pathLogDir.string(), pathErrorFile.string());
unsigned int nEnvFlags = 0;
if (GetBoolArg("-privdb", true))
nEnvFlags |= DB_PRIVATE;
dbenv.set_lg_dir(pathLogDir.string().c_str());
dbenv.set_cachesize(0, 0x100000, 1); // 1 MiB should be enough for just the wallet
dbenv.set_lg_bsize(0x10000);
dbenv.set_lg_max(1048576);
dbenv.set_lk_max_locks(40000);
dbenv.set_lk_max_objects(40000);
dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
dbenv.set_flags(DB_AUTO_COMMIT, 1);
dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
int ret = dbenv.open(path.string().c_str(),
DB_CREATE |
DB_INIT_LOCK |
DB_INIT_LOG |
DB_INIT_MPOOL |
DB_INIT_TXN |
DB_THREAD |
DB_RECOVER |
nEnvFlags,
S_IRUSR | S_IWUSR);
if (ret != 0)
return error("CDBEnv::Open : Error %d opening database environment: %s\n", ret, DbEnv::strerror(ret));
fDbEnvInit = true;
fMockDb = false;
return true;
}
void CDBEnv::MakeMock()
{
if (fDbEnvInit)
throw runtime_error("CDBEnv::MakeMock : Already initialized");
boost::this_thread::interruption_point();
LogPrint("db", "CDBEnv::MakeMock\n");
dbenv.set_cachesize(1, 0, 1);
dbenv.set_lg_bsize(10485760 * 4);
dbenv.set_lg_max(10485760);
dbenv.set_lk_max_locks(10000);
dbenv.set_lk_max_objects(10000);
dbenv.set_flags(DB_AUTO_COMMIT, 1);
dbenv.log_set_config(DB_LOG_IN_MEMORY, 1);
int ret = dbenv.open(NULL,
DB_CREATE |
DB_INIT_LOCK |
DB_INIT_LOG |
DB_INIT_MPOOL |
DB_INIT_TXN |
DB_THREAD |
DB_PRIVATE,
S_IRUSR | S_IWUSR);
if (ret > 0)
throw runtime_error(strprintf("CDBEnv::MakeMock : Error %d opening database environment.", ret));
fDbEnvInit = true;
fMockDb = true;
}
CDBEnv::VerifyResult CDBEnv::Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile))
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
Db db(&dbenv, 0);
int result = db.verify(strFile.c_str(), NULL, NULL, 0);
if (result == 0)
return VERIFY_OK;
else if (recoverFunc == NULL)
return RECOVER_FAIL;
// Try to recover:
bool fRecovered = (*recoverFunc)(*this, strFile);
return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
}
bool CDBEnv::Salvage(std::string strFile, bool fAggressive, std::vector<CDBEnv::KeyValPair>& vResult)
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
u_int32_t flags = DB_SALVAGE;
if (fAggressive)
flags |= DB_AGGRESSIVE;
stringstream strDump;
Db db(&dbenv, 0);
int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
if (result == DB_VERIFY_BAD) {
LogPrintf("CDBEnv::Salvage : Database salvage found errors, all data may not be recoverable.\n");
if (!fAggressive) {
LogPrintf("CDBEnv::Salvage : Rerun with aggressive mode to ignore errors and continue.\n");
return false;
}
}
if (result != 0 && result != DB_VERIFY_BAD) {
LogPrintf("CDBEnv::Salvage : Database salvage failed with result %d.\n", result);
return false;
}
// Format of bdb dump is ascii lines:
// header lines...
// HEADER=END
// hexadecimal key
// hexadecimal value
// ... repeated
// DATA=END
string strLine;
while (!strDump.eof() && strLine != "HEADER=END")
getline(strDump, strLine); // Skip past header
std::string keyHex, valueHex;
while (!strDump.eof() && keyHex != "DATA=END") {
getline(strDump, keyHex);
if (keyHex != "DATA_END") {
getline(strDump, valueHex);
vResult.push_back(make_pair(ParseHex(keyHex), ParseHex(valueHex)));
}
}
return (result == 0);
}
void CDBEnv::CheckpointLSN(const std::string& strFile)
{
dbenv.txn_checkpoint(0, 0, 0);
if (fMockDb)
return;
dbenv.lsn_reset(strFile.c_str(), 0);
}
CDB::CDB(const std::string& strFilename, const char* pszMode) : pdb(NULL), activeTxn(NULL)
{
int ret;
fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
if (strFilename.empty())
return;
bool fCreate = strchr(pszMode, 'c') != NULL;
unsigned int nFlags = DB_THREAD;
if (fCreate)
nFlags |= DB_CREATE;
{
LOCK(bitdb.cs_db);
if (!bitdb.Open(GetDataDir()))
throw runtime_error("CDB : Failed to open database environment.");
strFile = strFilename;
++bitdb.mapFileUseCount[strFile];
pdb = bitdb.mapDb[strFile];
if (pdb == NULL) {
pdb = new Db(&bitdb.dbenv, 0);
bool fMockDb = bitdb.IsMock();
if (fMockDb) {
DbMpoolFile* mpf = pdb->get_mpf();
ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
if (ret != 0)
throw runtime_error(strprintf("CDB : Failed to configure for no temp file backing for database %s", strFile));
}
ret = pdb->open(NULL, // Txn pointer
fMockDb ? NULL : strFile.c_str(), // Filename
fMockDb ? strFile.c_str() : "main", // Logical db name
DB_BTREE, // Database type
nFlags, // Flags
0);
if (ret != 0) {
delete pdb;
pdb = NULL;
--bitdb.mapFileUseCount[strFile];
strFile = "";
throw runtime_error(strprintf("CDB : Error %d, can't open database %s", ret, strFile));
}
if (fCreate && !Exists(string("version"))) {
bool fTmp = fReadOnly;
fReadOnly = false;
WriteVersion(CLIENT_VERSION);
fReadOnly = fTmp;
}
bitdb.mapDb[strFile] = pdb;
}
}
}
void CDB::Flush()
{
if (activeTxn)
return;
// Flush database activity from memory pool to disk log
unsigned int nMinutes = 0;
if (fReadOnly)
nMinutes = 1;
bitdb.dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100) * 1024 : 0, nMinutes, 0);
}
void CDB::Close()
{
if (!pdb)
return;
if (activeTxn)
activeTxn->abort();
activeTxn = NULL;
pdb = NULL;
Flush();
{
LOCK(bitdb.cs_db);
--bitdb.mapFileUseCount[strFile];
}
}
void CDBEnv::CloseDb(const string& strFile)
{
{
LOCK(cs_db);
if (mapDb[strFile] != NULL) {
// Close the database handle
Db* pdb = mapDb[strFile];
pdb->close(0);
delete pdb;
mapDb[strFile] = NULL;
}
}
}
bool CDBEnv::RemoveDb(const string& strFile)
{
this->CloseDb(strFile);
LOCK(cs_db);
int rc = dbenv.dbremove(NULL, strFile.c_str(), NULL, DB_AUTO_COMMIT);
return (rc == 0);
}
bool CDB::Rewrite(const string& strFile, const char* pszSkip)
{
while (true) {
{
LOCK(bitdb.cs_db);
if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0) {
// Flush log data to the dat file
bitdb.CloseDb(strFile);
bitdb.CheckpointLSN(strFile);
bitdb.mapFileUseCount.erase(strFile);
bool fSuccess = true;
LogPrintf("CDB::Rewrite : Rewriting %s...\n", strFile);
string strFileRes = strFile + ".rewrite";
{ // surround usage of db with extra {}
CDB db(strFile.c_str(), "r");
Db* pdbCopy = new Db(&bitdb.dbenv, 0);
int ret = pdbCopy->open(NULL, // Txn pointer
strFileRes.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0) {
LogPrintf("CDB::Rewrite : Can't create database file %s\n", strFileRes);
fSuccess = false;
}
Dbc* pcursor = db.GetCursor();
if (pcursor)
while (fSuccess) {
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
if (ret == DB_NOTFOUND) {
pcursor->close();
break;
} else if (ret != 0) {
pcursor->close();
fSuccess = false;
break;
}
if (pszSkip &&
strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
continue;
if (strncmp(&ssKey[0], "\x07version", 8) == 0) {
// Update version:
ssValue.clear();
ssValue << CLIENT_VERSION;
}
Dbt datKey(&ssKey[0], ssKey.size());
Dbt datValue(&ssValue[0], ssValue.size());
int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
if (fSuccess) {
db.Close();
bitdb.CloseDb(strFile);
if (pdbCopy->close(0))
fSuccess = false;
delete pdbCopy;
}
}
if (fSuccess) {
Db dbA(&bitdb.dbenv, 0);
if (dbA.remove(strFile.c_str(), NULL, 0))
fSuccess = false;
Db dbB(&bitdb.dbenv, 0);
if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
fSuccess = false;
}
if (!fSuccess)
LogPrintf("CDB::Rewrite : Failed to rewrite database file %s\n", strFileRes);
return fSuccess;
}
}
MilliSleep(100);
}
return false;
}
void CDBEnv::Flush(bool fShutdown)
{
int64_t nStart = GetTimeMillis();
// Flush log data to the actual data file on all files that are not in use
LogPrint("db", "CDBEnv::Flush : Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started");
if (!fDbEnvInit)
return;
{
LOCK(cs_db);
map<string, int>::iterator mi = mapFileUseCount.begin();
while (mi != mapFileUseCount.end()) {
string strFile = (*mi).first;
int nRefCount = (*mi).second;
LogPrint("db", "CDBEnv::Flush : Flushing %s (refcount = %d)...\n", strFile, nRefCount);
if (nRefCount == 0) {
// Move log data to the dat file
CloseDb(strFile);
LogPrint("db", "CDBEnv::Flush : %s checkpoint\n", strFile);
dbenv.txn_checkpoint(0, 0, 0);
LogPrint("db", "CDBEnv::Flush : %s detach\n", strFile);
if (!fMockDb)
dbenv.lsn_reset(strFile.c_str(), 0);
LogPrint("db", "CDBEnv::Flush : %s closed\n", strFile);
mapFileUseCount.erase(mi++);
} else
mi++;
}
LogPrint("db", "CDBEnv::Flush : Flush(%s)%s took %15dms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started", GetTimeMillis() - nStart);
if (fShutdown) {
char** listp;
if (mapFileUseCount.empty()) {
dbenv.log_archive(&listp, DB_ARCH_REMOVE);
Close();
if (!fMockDb)
boost::filesystem::remove_all(path / "database");
}
}
}
}
<commit_msg>[walletdb] Fix syntax error in key parser<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "db.h"
#include "addrman.h"
#include "hash.h"
#include "protocol.h"
#include "util.h"
#include "utilstrencodings.h"
#include <stdint.h>
#ifndef WIN32
#include <sys/stat.h>
#endif
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
#include <boost/version.hpp>
#include <openssl/rand.h>
using namespace std;
using namespace boost;
unsigned int nWalletDBUpdated;
//
// CDB
//
CDBEnv bitdb;
void CDBEnv::EnvShutdown()
{
if (!fDbEnvInit)
return;
fDbEnvInit = false;
int ret = dbenv.close(0);
if (ret != 0)
LogPrintf("CDBEnv::EnvShutdown : Error %d shutting down database environment: %s\n", ret, DbEnv::strerror(ret));
if (!fMockDb)
DbEnv(0).remove(path.string().c_str(), 0);
}
CDBEnv::CDBEnv() : dbenv(DB_CXX_NO_EXCEPTIONS)
{
fDbEnvInit = false;
fMockDb = false;
}
CDBEnv::~CDBEnv()
{
EnvShutdown();
}
void CDBEnv::Close()
{
EnvShutdown();
}
bool CDBEnv::Open(const boost::filesystem::path& pathIn)
{
if (fDbEnvInit)
return true;
boost::this_thread::interruption_point();
path = pathIn;
filesystem::path pathLogDir = path / "database";
TryCreateDirectory(pathLogDir);
filesystem::path pathErrorFile = path / "db.log";
LogPrintf("CDBEnv::Open : LogDir=%s ErrorFile=%s\n", pathLogDir.string(), pathErrorFile.string());
unsigned int nEnvFlags = 0;
if (GetBoolArg("-privdb", true))
nEnvFlags |= DB_PRIVATE;
dbenv.set_lg_dir(pathLogDir.string().c_str());
dbenv.set_cachesize(0, 0x100000, 1); // 1 MiB should be enough for just the wallet
dbenv.set_lg_bsize(0x10000);
dbenv.set_lg_max(1048576);
dbenv.set_lk_max_locks(40000);
dbenv.set_lk_max_objects(40000);
dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
dbenv.set_flags(DB_AUTO_COMMIT, 1);
dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
int ret = dbenv.open(path.string().c_str(),
DB_CREATE |
DB_INIT_LOCK |
DB_INIT_LOG |
DB_INIT_MPOOL |
DB_INIT_TXN |
DB_THREAD |
DB_RECOVER |
nEnvFlags,
S_IRUSR | S_IWUSR);
if (ret != 0)
return error("CDBEnv::Open : Error %d opening database environment: %s\n", ret, DbEnv::strerror(ret));
fDbEnvInit = true;
fMockDb = false;
return true;
}
void CDBEnv::MakeMock()
{
if (fDbEnvInit)
throw runtime_error("CDBEnv::MakeMock : Already initialized");
boost::this_thread::interruption_point();
LogPrint("db", "CDBEnv::MakeMock\n");
dbenv.set_cachesize(1, 0, 1);
dbenv.set_lg_bsize(10485760 * 4);
dbenv.set_lg_max(10485760);
dbenv.set_lk_max_locks(10000);
dbenv.set_lk_max_objects(10000);
dbenv.set_flags(DB_AUTO_COMMIT, 1);
dbenv.log_set_config(DB_LOG_IN_MEMORY, 1);
int ret = dbenv.open(NULL,
DB_CREATE |
DB_INIT_LOCK |
DB_INIT_LOG |
DB_INIT_MPOOL |
DB_INIT_TXN |
DB_THREAD |
DB_PRIVATE,
S_IRUSR | S_IWUSR);
if (ret > 0)
throw runtime_error(strprintf("CDBEnv::MakeMock : Error %d opening database environment.", ret));
fDbEnvInit = true;
fMockDb = true;
}
CDBEnv::VerifyResult CDBEnv::Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile))
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
Db db(&dbenv, 0);
int result = db.verify(strFile.c_str(), NULL, NULL, 0);
if (result == 0)
return VERIFY_OK;
else if (recoverFunc == NULL)
return RECOVER_FAIL;
// Try to recover:
bool fRecovered = (*recoverFunc)(*this, strFile);
return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
}
bool CDBEnv::Salvage(std::string strFile, bool fAggressive, std::vector<CDBEnv::KeyValPair>& vResult)
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
u_int32_t flags = DB_SALVAGE;
if (fAggressive)
flags |= DB_AGGRESSIVE;
stringstream strDump;
Db db(&dbenv, 0);
int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
if (result == DB_VERIFY_BAD) {
LogPrintf("CDBEnv::Salvage : Database salvage found errors, all data may not be recoverable.\n");
if (!fAggressive) {
LogPrintf("CDBEnv::Salvage : Rerun with aggressive mode to ignore errors and continue.\n");
return false;
}
}
if (result != 0 && result != DB_VERIFY_BAD) {
LogPrintf("CDBEnv::Salvage : Database salvage failed with result %d.\n", result);
return false;
}
// Format of bdb dump is ascii lines:
// header lines...
// HEADER=END
// hexadecimal key
// hexadecimal value
// ... repeated
// DATA=END
string strLine;
while (!strDump.eof() && strLine != "HEADER=END")
getline(strDump, strLine); // Skip past header
std::string keyHex, valueHex;
while (!strDump.eof() && keyHex != "DATA=END") {
getline(strDump, keyHex);
if (keyHex != "DATA=END") {
getline(strDump, valueHex);
vResult.push_back(make_pair(ParseHex(keyHex), ParseHex(valueHex)));
}
}
return (result == 0);
}
void CDBEnv::CheckpointLSN(const std::string& strFile)
{
dbenv.txn_checkpoint(0, 0, 0);
if (fMockDb)
return;
dbenv.lsn_reset(strFile.c_str(), 0);
}
CDB::CDB(const std::string& strFilename, const char* pszMode) : pdb(NULL), activeTxn(NULL)
{
int ret;
fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
if (strFilename.empty())
return;
bool fCreate = strchr(pszMode, 'c') != NULL;
unsigned int nFlags = DB_THREAD;
if (fCreate)
nFlags |= DB_CREATE;
{
LOCK(bitdb.cs_db);
if (!bitdb.Open(GetDataDir()))
throw runtime_error("CDB : Failed to open database environment.");
strFile = strFilename;
++bitdb.mapFileUseCount[strFile];
pdb = bitdb.mapDb[strFile];
if (pdb == NULL) {
pdb = new Db(&bitdb.dbenv, 0);
bool fMockDb = bitdb.IsMock();
if (fMockDb) {
DbMpoolFile* mpf = pdb->get_mpf();
ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
if (ret != 0)
throw runtime_error(strprintf("CDB : Failed to configure for no temp file backing for database %s", strFile));
}
ret = pdb->open(NULL, // Txn pointer
fMockDb ? NULL : strFile.c_str(), // Filename
fMockDb ? strFile.c_str() : "main", // Logical db name
DB_BTREE, // Database type
nFlags, // Flags
0);
if (ret != 0) {
delete pdb;
pdb = NULL;
--bitdb.mapFileUseCount[strFile];
strFile = "";
throw runtime_error(strprintf("CDB : Error %d, can't open database %s", ret, strFile));
}
if (fCreate && !Exists(string("version"))) {
bool fTmp = fReadOnly;
fReadOnly = false;
WriteVersion(CLIENT_VERSION);
fReadOnly = fTmp;
}
bitdb.mapDb[strFile] = pdb;
}
}
}
void CDB::Flush()
{
if (activeTxn)
return;
// Flush database activity from memory pool to disk log
unsigned int nMinutes = 0;
if (fReadOnly)
nMinutes = 1;
bitdb.dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100) * 1024 : 0, nMinutes, 0);
}
void CDB::Close()
{
if (!pdb)
return;
if (activeTxn)
activeTxn->abort();
activeTxn = NULL;
pdb = NULL;
Flush();
{
LOCK(bitdb.cs_db);
--bitdb.mapFileUseCount[strFile];
}
}
void CDBEnv::CloseDb(const string& strFile)
{
{
LOCK(cs_db);
if (mapDb[strFile] != NULL) {
// Close the database handle
Db* pdb = mapDb[strFile];
pdb->close(0);
delete pdb;
mapDb[strFile] = NULL;
}
}
}
bool CDBEnv::RemoveDb(const string& strFile)
{
this->CloseDb(strFile);
LOCK(cs_db);
int rc = dbenv.dbremove(NULL, strFile.c_str(), NULL, DB_AUTO_COMMIT);
return (rc == 0);
}
bool CDB::Rewrite(const string& strFile, const char* pszSkip)
{
while (true) {
{
LOCK(bitdb.cs_db);
if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0) {
// Flush log data to the dat file
bitdb.CloseDb(strFile);
bitdb.CheckpointLSN(strFile);
bitdb.mapFileUseCount.erase(strFile);
bool fSuccess = true;
LogPrintf("CDB::Rewrite : Rewriting %s...\n", strFile);
string strFileRes = strFile + ".rewrite";
{ // surround usage of db with extra {}
CDB db(strFile.c_str(), "r");
Db* pdbCopy = new Db(&bitdb.dbenv, 0);
int ret = pdbCopy->open(NULL, // Txn pointer
strFileRes.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0) {
LogPrintf("CDB::Rewrite : Can't create database file %s\n", strFileRes);
fSuccess = false;
}
Dbc* pcursor = db.GetCursor();
if (pcursor)
while (fSuccess) {
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
if (ret == DB_NOTFOUND) {
pcursor->close();
break;
} else if (ret != 0) {
pcursor->close();
fSuccess = false;
break;
}
if (pszSkip &&
strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
continue;
if (strncmp(&ssKey[0], "\x07version", 8) == 0) {
// Update version:
ssValue.clear();
ssValue << CLIENT_VERSION;
}
Dbt datKey(&ssKey[0], ssKey.size());
Dbt datValue(&ssValue[0], ssValue.size());
int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
if (fSuccess) {
db.Close();
bitdb.CloseDb(strFile);
if (pdbCopy->close(0))
fSuccess = false;
delete pdbCopy;
}
}
if (fSuccess) {
Db dbA(&bitdb.dbenv, 0);
if (dbA.remove(strFile.c_str(), NULL, 0))
fSuccess = false;
Db dbB(&bitdb.dbenv, 0);
if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
fSuccess = false;
}
if (!fSuccess)
LogPrintf("CDB::Rewrite : Failed to rewrite database file %s\n", strFileRes);
return fSuccess;
}
}
MilliSleep(100);
}
return false;
}
void CDBEnv::Flush(bool fShutdown)
{
int64_t nStart = GetTimeMillis();
// Flush log data to the actual data file on all files that are not in use
LogPrint("db", "CDBEnv::Flush : Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started");
if (!fDbEnvInit)
return;
{
LOCK(cs_db);
map<string, int>::iterator mi = mapFileUseCount.begin();
while (mi != mapFileUseCount.end()) {
string strFile = (*mi).first;
int nRefCount = (*mi).second;
LogPrint("db", "CDBEnv::Flush : Flushing %s (refcount = %d)...\n", strFile, nRefCount);
if (nRefCount == 0) {
// Move log data to the dat file
CloseDb(strFile);
LogPrint("db", "CDBEnv::Flush : %s checkpoint\n", strFile);
dbenv.txn_checkpoint(0, 0, 0);
LogPrint("db", "CDBEnv::Flush : %s detach\n", strFile);
if (!fMockDb)
dbenv.lsn_reset(strFile.c_str(), 0);
LogPrint("db", "CDBEnv::Flush : %s closed\n", strFile);
mapFileUseCount.erase(mi++);
} else
mi++;
}
LogPrint("db", "CDBEnv::Flush : Flush(%s)%s took %15dms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started", GetTimeMillis() - nStart);
if (fShutdown) {
char** listp;
if (mapFileUseCount.empty()) {
dbenv.log_archive(&listp, DB_ARCH_REMOVE);
Close();
if (!fMockDb)
boost::filesystem::remove_all(path / "database");
}
}
}
}
<|endoftext|> |
<commit_before>
#include <stdio.h>
#include "charset.h"
#include "str.h"
#include "contain.h"
#include "except.h"
#include "source.h"
#include "baseobj.h"
// ------------------------------------------------------------------------ //
// --- TOKEN EXTRACTOR ---------------------------------------------------- //
// ------------------------------------------------------------------------ //
class EParser: public EMessage
{
protected:
string filename;
int linenum;
public:
EParser(const string& ifilename, int ilinenum, const string& msg)
: EMessage(msg), filename(ifilename), linenum(ilinenum) { }
virtual ~EParser() throw();
virtual string what() const throw();
};
enum Token
{
tokUndefined = -1,
tokBlockBegin, tokBlockEnd, tokEnd, // these depend on C-style vs. Python-style mode
tokEof,
tokIdent, tokIntValue, tokStrValue,
tokComma, tokPeriod, tokDiv
};
enum SyntaxMode { syntaxIndent, syntaxCurly };
class Parser
{
protected:
InText* input;
Stack<int> indentStack;
void parseStringLiteral();
void skipMultilineComment();
public:
SyntaxMode mode;
bool singleLineBlock; // only for syntaxIndent, e.g. if a: b = c
Token token;
string strValue;
ularge intValue;
Parser(const string& filename);
~Parser();
Token next() throw(EParser, ESysError);
void error(const string& msg) throw(EParser);
void syntax(const string& msg) throw(EParser);
int indentLevel() { return indentStack.top(); }
};
// ------------------------------------------------------------------------ //
EParser::~EParser() throw() { }
string EParser::what() const throw()
{
string s;
if (!filename.empty())
s = filename + '(' + itostring(linenum) + "): ";
return s + EMessage::what();
}
const charset wsChars = "\t ";
const charset identFirst = "A-Za-z_";
const charset identRest = "0-9A-Za-z_";
const charset digits = "0-9";
const charset hexDigits = "0-9A-Fa-f";
const charset printableChars = "~20-~FF";
static string mkPrintable(char c)
{
if (c == '\\')
return string("\\\\");
else if (c == '\'')
return string("\\\'");
else if (printableChars[c])
return string(c);
else
return "\\x" + itostring(unsigned(c), 16);
}
Parser::Parser(const string& filename)
: input(new InFile(filename)),
indentStack(), mode(syntaxIndent), singleLineBlock(false),
token(tokUndefined), strValue(), intValue(0)
{
indentStack.push(0);
}
Parser::~Parser()
{
delete input;
}
void Parser::error(const string& msg) throw(EParser)
{
throw EParser(input->getFileName(), input->getLinenum(), msg);
}
void Parser::syntax(const string& msg) throw(EParser)
{
error("Syntax error: " + msg);
}
void Parser::parseStringLiteral()
{
static const charset stringChars = printableChars - charset("'\\");
strValue.clear();
while (true)
{
strValue += input->token(stringChars);
if (input->getEof())
syntax("Unexpected end of file in string literal");
char c = input->get();
if (input->isEolChar(c))
syntax("Unexpected end of line in string literal");
if (c == '\'')
return;
else if (c == '\\')
{
c = input->get();
if (c == 't')
strValue += '\t';
else if (c == 'r')
strValue += '\r';
else if (c == 'n')
strValue += '\n';
else if (c == 'x')
{
string s;
if (hexDigits[input->preview()])
{
s += input->get();
if (hexDigits[input->preview()])
s += input->get();
bool e, o;
ularge value = stringtou(s.c_str(), &e, &o, 16);
strValue += char(value);
}
else
syntax("Malformed hex sequence");
}
else
strValue += c;
}
else
syntax("Illegal character in string literal '" + mkPrintable(c) + "'");
}
}
void Parser::skipMultilineComment()
{
static const charset commentChars = (printableChars - '}') + wsChars;
while (true)
{
input->skip(commentChars);
if (input->getEol())
{
if (input->getEof())
error("Unexpected end of file in comments");
input->skipEol();
continue;
}
char e = input->get();
if (e == '}')
{
if (input->preview() == '#')
{
input->get();
break;
}
}
else
syntax("Illegal character in comments '" + mkPrintable(e) + "'");
}
input->skip(wsChars);
if (!input->getEol())
syntax("Multiline comments must end with a new line");
input->skipEol();
}
Token Parser::next() throw(EParser, ESysError)
{
restart:
strValue.clear();
input->skip(wsChars);
char c = input->preview();
// --- Handle EOF and EOL ---
if (input->getEof())
{
// finalize all indents at end of file
if (mode == syntaxIndent && indentStack.size() > 1)
{
strValue = "<END>";
indentStack.pop();
return token = tokBlockEnd;
}
strValue = "<EOF>";
return token = tokEof;
}
else if (input->getEol())
{
input->skipEol();
if (mode == syntaxIndent)
{
if (singleLineBlock)
{
strValue = "<END>";
singleLineBlock = false;
return token = tokBlockEnd;
}
else
{
strValue = "<SEP>";
return token = tokEnd;
}
}
else
goto restart;
}
else if (c == '#')
{
input->get();
if (input->preview() == '{')
skipMultilineComment();
else
input->skipLine();
goto restart;
}
else if (mode == syntaxIndent && input->getNewLine())
{
// this is a new line, blanks are skipped, so we are at the first
// non-blank char:
int newIndent = input->getIndent();
int oldIndent = indentStack.top();
if (newIndent > oldIndent)
{
strValue = "<BEGIN>";
indentStack.push(newIndent);
input->resetNewLine();
return token = tokBlockBegin;
}
else if (newIndent < oldIndent)
{
strValue = "<END>";
indentStack.pop();
oldIndent = indentStack.top();
if (newIndent > oldIndent)
syntax("Unmatched un-indent");
else if (newIndent == oldIndent)
{
input->resetNewLine();
return token = tokBlockEnd;
}
else
return token = tokBlockEnd;
}
// else: pass through to token analysis
}
// --- Handle ordinary tokens ---
if (identFirst[c]) // identifier or keyword
{
strValue = input->get();
strValue += input->token(identRest);
return token = tokIdent;
}
else if (digits[c]) // numeric
{
strValue = input->token(digits);
bool e, o;
intValue = stringtou(strValue.c_str(), &e, &o, 10);
if (e)
error("'" + strValue + "' is not a valid number");
if (o)
error("Numeric overflow (" + strValue + ")");
return token = tokIntValue;
}
else // special chars
{
strValue = input->get();
switch (c)
{
case ',': return token = tokComma;
case '.': return token = tokPeriod;
case '\'': parseStringLiteral(); return token = tokStrValue;
case ';': strValue = "<SEP>"; return token = tokEnd;
case ':':
mode = syntaxIndent;
input->skip(wsChars);
singleLineBlock = !input->getEol();
return token = tokBlockBegin;
case '/': return token = tokDiv;
}
}
syntax("Illegal character '" + mkPrintable(c) + "'");
return tokUndefined;
}
class _AtExit
{
public:
~_AtExit()
{
if (Base::objCount != 0)
fprintf(stderr, "Internal: objCount = %d\n", Base::objCount);
if (stralloc != 0)
fprintf(stderr, "Internal: stralloc = %d\n", stralloc);
if (FifoChunk::chunkCount != 0)
fprintf(stderr, "Internal: chunkCount = %d\n", FifoChunk::chunkCount);
}
} _atexit;
int main()
{
Parser parser("tests/parser.txt");
try
{
while (parser.next() != tokEof)
{
printf("%s ", parser.strValue.c_str());
if (parser.token == tokBlockBegin || parser.token == tokBlockEnd || parser.token == tokEnd)
printf("\n");
}
}
catch (Exception& e)
{
fprintf(stderr, "%s\n", e.what().c_str());
}
return 0;
}
<commit_msg>Will not support C-style blocks yet, too complicated. Later maybe.<commit_after>
#include <stdio.h>
#include "charset.h"
#include "str.h"
#include "contain.h"
#include "except.h"
#include "source.h"
#include "baseobj.h"
// ------------------------------------------------------------------------ //
// --- TOKEN EXTRACTOR ---------------------------------------------------- //
// ------------------------------------------------------------------------ //
class EParser: public EMessage
{
protected:
string filename;
int linenum;
public:
EParser(const string& ifilename, int ilinenum, const string& msg)
: EMessage(msg), filename(ifilename), linenum(ilinenum) { }
virtual ~EParser() throw();
virtual string what() const throw();
};
enum Token
{
tokUndefined = -1,
tokBlockBegin, tokBlockEnd, tokEnd, // these will depend on C-style vs. Python-style modes in the future
tokEof,
tokIdent, tokIntValue, tokStrValue,
tokComma, tokPeriod, tokDiv
};
enum SyntaxMode { syntaxIndent, syntaxCurly };
class Parser
{
protected:
InText* input;
Stack<int> indentStack;
void parseStringLiteral();
void skipMultilineComment();
public:
bool singleLineBlock; // if a: b = c
Token token;
string strValue;
ularge intValue;
Parser(const string& filename);
~Parser();
Token next(bool expectBlock = false) throw(EParser, ESysError);
void error(const string& msg) throw(EParser);
void syntax(const string& msg) throw(EParser);
int indentLevel() { return indentStack.top(); }
};
// ------------------------------------------------------------------------ //
EParser::~EParser() throw() { }
string EParser::what() const throw()
{
string s;
if (!filename.empty())
s = filename + '(' + itostring(linenum) + "): ";
return s + EMessage::what();
}
const charset wsChars = "\t ";
const charset identFirst = "A-Za-z_";
const charset identRest = "0-9A-Za-z_";
const charset digits = "0-9";
const charset hexDigits = "0-9A-Fa-f";
const charset printableChars = "~20-~FF";
static string mkPrintable(char c)
{
if (c == '\\')
return string("\\\\");
else if (c == '\'')
return string("\\\'");
else if (printableChars[c])
return string(c);
else
return "\\x" + itostring(unsigned(c), 16);
}
Parser::Parser(const string& filename)
: input(new InFile(filename)),
indentStack(), singleLineBlock(false),
token(tokUndefined), strValue(), intValue(0)
{
indentStack.push(0);
}
Parser::~Parser()
{
delete input;
}
void Parser::error(const string& msg) throw(EParser)
{
throw EParser(input->getFileName(), input->getLinenum(), msg);
}
void Parser::syntax(const string& msg) throw(EParser)
{
error("Syntax error: " + msg);
}
void Parser::parseStringLiteral()
{
static const charset stringChars = printableChars - charset("'\\");
strValue.clear();
while (true)
{
strValue += input->token(stringChars);
if (input->getEof())
syntax("Unexpected end of file in string literal");
char c = input->get();
if (input->isEolChar(c))
syntax("Unexpected end of line in string literal");
if (c == '\'')
return;
else if (c == '\\')
{
c = input->get();
if (c == 't')
strValue += '\t';
else if (c == 'r')
strValue += '\r';
else if (c == 'n')
strValue += '\n';
else if (c == 'x')
{
string s;
if (hexDigits[input->preview()])
{
s += input->get();
if (hexDigits[input->preview()])
s += input->get();
bool e, o;
ularge value = stringtou(s.c_str(), &e, &o, 16);
strValue += char(value);
}
else
syntax("Malformed hex sequence");
}
else
strValue += c;
}
else
syntax("Illegal character in string literal '" + mkPrintable(c) + "'");
}
}
void Parser::skipMultilineComment()
{
static const charset commentChars = (printableChars - '}') + wsChars;
while (true)
{
input->skip(commentChars);
if (input->getEol())
{
if (input->getEof())
error("Unexpected end of file in comments");
input->skipEol();
continue;
}
char e = input->get();
if (e == '}')
{
if (input->preview() == '#')
{
input->get();
break;
}
}
else
syntax("Illegal character in comments '" + mkPrintable(e) + "'");
}
input->skip(wsChars);
if (!input->getEol())
syntax("Multiline comments must end with a new line");
input->skipEol();
}
Token Parser::next(bool expectBlock) throw(EParser, ESysError)
{
restart:
strValue.clear();
input->skip(wsChars);
char c = input->preview();
// --- Handle EOF and EOL ---
if (input->getEof())
{
// finalize all indents at end of file
if (indentStack.size() > 1)
{
strValue = "<END>";
indentStack.pop();
return token = tokBlockEnd;
}
strValue = "<EOF>";
return token = tokEof;
}
else if (input->getEol())
{
input->skipEol();
if (singleLineBlock)
{
strValue = "<END>";
singleLineBlock = false;
return token = tokBlockEnd;
}
else
{
strValue = "<SEP>";
return token = tokEnd;
}
}
else if (c == '#')
{
input->get();
if (input->preview() == '{')
skipMultilineComment();
else
input->skipLine();
goto restart;
}
else if (input->getNewLine())
{
// this is a new line, blanks are skipped, so we are at the first
// non-blank char:
int newIndent = input->getIndent();
int oldIndent = indentStack.top();
if (newIndent > oldIndent)
{
strValue = "<BEGIN>";
indentStack.push(newIndent);
input->resetNewLine();
return token = tokBlockBegin;
}
else if (newIndent < oldIndent)
{
strValue = "<END>";
indentStack.pop();
oldIndent = indentStack.top();
if (newIndent > oldIndent)
syntax("Unmatched un-indent");
else if (newIndent == oldIndent)
{
input->resetNewLine();
return token = tokBlockEnd;
}
else
return token = tokBlockEnd;
}
// else: pass through to token analysis
}
// --- Handle ordinary tokens ---
if (identFirst[c]) // identifier or keyword
{
strValue = input->get();
strValue += input->token(identRest);
return token = tokIdent;
}
else if (digits[c]) // numeric
{
strValue = input->token(digits);
bool e, o;
intValue = stringtou(strValue.c_str(), &e, &o, 10);
if (e)
error("'" + strValue + "' is not a valid number");
if (o)
error("Numeric overflow (" + strValue + ")");
return token = tokIntValue;
}
else // special chars
{
strValue = input->get();
switch (c)
{
case ',': return token = tokComma;
case '.': return token = tokPeriod;
case '\'': parseStringLiteral(); return token = tokStrValue;
case ';': strValue = "<SEP>"; return token = tokEnd;
case ':':
if (!expectBlock)
syntax("Nested block expected");
input->skip(wsChars);
singleLineBlock = !input->getEol();
return token = tokBlockBegin;
case '/': return token = tokDiv;
}
}
syntax("Illegal character '" + mkPrintable(c) + "'");
return tokUndefined;
}
class _AtExit
{
public:
~_AtExit()
{
if (Base::objCount != 0)
fprintf(stderr, "Internal: objCount = %d\n", Base::objCount);
if (stralloc != 0)
fprintf(stderr, "Internal: stralloc = %d\n", stralloc);
if (FifoChunk::chunkCount != 0)
fprintf(stderr, "Internal: chunkCount = %d\n", FifoChunk::chunkCount);
}
} _atexit;
int main()
{
Parser parser("tests/parser.txt");
try
{
while (parser.next() != tokEof)
{
printf("%s ", parser.strValue.c_str());
if (parser.token == tokBlockBegin || parser.token == tokBlockEnd || parser.token == tokEnd)
printf("\n");
}
}
catch (Exception& e)
{
fprintf(stderr, "%s\n", e.what().c_str());
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <oauth.h>
#include <opencv2/opencv.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/superres/optical_flow.hpp>
#include "tweet.h"
#include "webclient.h"
// #include "mykey.h"
#include "jphacks_key.h"
int main(void)
{
// buffering off for debug on pty
setvbuf( stdout, NULL, _IONBF, BUFSIZ );
WebClient::initialize();
TwitterClient tc(c_key, c_sec, t_key, t_sec);
std::string filename("../../skeleton.png");
cv::Mat src = cv::imread(filename);
//return ( tc.tweet(message, src) ) ? 0 : 1;
return 0;
}
<commit_msg>optical flow から動体を検出する処理を追加<commit_after>/* main.cpp */
//-----------------------------------------------------------------------
//include files
//-----------------------------------------------------------------------
#include <iostream>
#include <oauth.h>
#include <thread>
#include <mutex>
#include <unistd.h>
#include <opencv2/opencv.hpp>
#include <opencv2/superres/optical_flow.hpp>
#include "sequentialCalcOptFlow.h"
#include "sequentialCaptCurrBuffer.h"
#include "tweet.h"
#include "webclient.h"
// #include "mykey.h"
#include "jphacks_key.h"
//-----------------------------------------------------------------------
// using namespace
//-----------------------------------------------------------------------
using namespace std;
//-----------------------------------------------------------------------
//***********************************************************************
// Function : main |
//***********************************************************************
int main(void)
{
// buffering off for debug on pty
setvbuf( stdout, NULL, _IONBF, BUFSIZ );
WebClient::initialize();
TwitterClient tc(c_key, c_sec, t_key, t_sec);
std::string filename("../../skeleton.png");
cv::Mat src = cv::imread(filename);
// current frame の連続取得(別スレッド)
cv::Mat curr_tmp;
bool break_flag = false;
thread cap_th( sequentialCaptCurrBuffer, ref(curr_tmp), ref(break_flag));
while( curr_tmp.empty() ){
sleep(0);
}
// optical flow の連続算出(別スレッド)
cv::Mat flow_tmp;
thread optflow_th( sequentialCalcOptFlow, ref(curr_tmp), ref(flow_tmp), ref(break_flag));
while( flow_tmp.empty() ){
sleep(0);
}
while( cv::waitKey(1) != '\x1b' ) {
cap_mtx.lock();
cv::Mat curr = curr_tmp.clone();
cap_mtx.unlock();
opt_flow_mtx.lock();
cv::Mat flow = flow_tmp.clone();
opt_flow_mtx.unlock();
cv::Mat flowXY[2];
split(flow, flowXY);
// オプティカルフローの可視化(色符号化)
// オプティカルフローを極座標に変換(角度は[deg])
cv::Mat magnitude, angle;
cv::cartToPolar(flowXY[0], flowXY[1], magnitude, angle, true);
double maxVal;
cv::minMaxLoc(magnitude, NULL, &maxVal, NULL, NULL);
// std::cout << maxVal << "\n";
// 色相(H)はオプティカルフローの角度
// 彩度(S)は0~1に正規化したオプティカルフローの大きさ
// 明度(V)は1
cv::Mat hsvPlanes[3];
hsvPlanes[0] = angle;
if(maxVal > 10){
cv::normalize(magnitude, hsvPlanes[2], 0, 1, cv::NORM_MINMAX); // 正規化
} else {
hsvPlanes[2] = cv::Mat::zeros(magnitude.size(), CV_32F);
}
hsvPlanes[1] = cv::Mat::ones(magnitude.size(), CV_32F);
// HSVを合成して一枚の画像にする
cv::Mat hsv;
merge(hsvPlanes, 3, hsv);
// HSVからBGRに変換
cv::Mat flowBgr;
cvtColor(hsv, flowBgr, cv::COLOR_HSV2BGR);
// 表示
cv::imshow("optical flow", flowBgr);
// グレースケール
cv::Mat gray, bin;
cv::cvtColor( flowBgr, gray, CV_BGR2GRAY);
cv::minMaxLoc(flowBgr, NULL, &maxVal, NULL, NULL);
// 平滑化
blur( gray, gray, cv::Size(3,3) );
cv::imshow("gray", gray);
// cv::threshold(cv::Mat1b(gray*255), bin, 0.0, 255.0, CV_THRESH_BINARY | CV_THRESH_OTSU);
cv::threshold(cv::Mat1b(gray*255), bin, 10, 255.0, CV_THRESH_BINARY);
cv::imshow("bin", bin);
//輪郭の座標リスト
std::vector< std::vector< cv::Point > > contours;
//輪郭取得
cv::findContours(bin, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
//cv::findContours(bin, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
// 検出された輪郭線を緑で描画
for (auto contour = contours.begin(); contour != contours.end(); contour++){
// cv::polylines(prev, *contour, true, cv::Scalar(0, 255, 0), 2);
//輪郭を直線近似する
std::vector< cv::Point > approx;
cv::approxPolyDP(cv::Mat(*contour), approx, 0.01 * cv::arcLength(*contour, true), true);
// 近似の面積が一定以上なら取得
double area = cv::contourArea(approx);
if (area > 1000.0){
cv::Rect brect = cv::boundingRect(cv::Mat(approx).reshape(2));
// 外接矩形を描画
cv::rectangle(curr, brect.tl(), brect.br(), cv::Scalar(255, 0, 0), 2, CV_AA);
// cv::polylines(curr, *contour, true, cv::Scalar(0, 255, 0), 2);
}
}
//全体を表示する場合
cv::imshow("coun", curr);
}
// スレッドの終了
break_flag = true;
cap_th.join();
optflow_th.join();
//return ( tc.tweet(message, src) ) ? 0 : 1;
return 0;
}
<|endoftext|> |
<commit_before>#include "ipc.h"
ObjHandle::ObjHandle(SegmentId segmentid, size_t size, IpcPointer ipcpointer)
: segmentid_(segmentid), size_(size), ipcpointer_(ipcpointer)
{}
MemorySegmentPool::MemorySegmentPool(bool create) : create_mode_(create) { }
// creates a memory segment if it is not already there; if the pool is in create mode,
// space is allocated, if it is in open mode, the shared memory is mapped into the process
void MemorySegmentPool::open_segment(SegmentId segmentid, size_t size) {
if (segmentid < segments_.size()) {
return;
}
segment_names_.resize(segmentid + 1);
segments_.resize(segmentid + 1);
std::string segment_name = std::string("segment:") + std::to_string(segmentid);
if (create_mode_) {
assert(size > 0);
shared_memory_object::remove(segment_name.c_str()); // remove segment if it has not been properly removed from last run
size_t new_size = (size / page_size_ + 2) * page_size_; // additional room for boost's bookkeeping
segments_[segmentid] = std::unique_ptr<managed_shared_memory>(new managed_shared_memory(create_only, segment_name.c_str(), new_size));
} else {
segments_[segmentid] = std::unique_ptr<managed_shared_memory>(new managed_shared_memory(open_only, segment_name.c_str()));
}
segment_names_[segmentid] = segment_name;
}
ObjHandle MemorySegmentPool::allocate(size_t size) {
// TODO(pcm): at the moment, this always creates a new segment, this will be changed
SegmentId segmentid = segment_names_.size();
open_segment(segmentid, size);
void* ptr = segments_[segmentid]->allocate(size);
auto handle = segments_[segmentid]->get_handle_from_address(ptr);
return ObjHandle(segmentid, size, handle);
}
// returns address of the object refered to by the handle, needs to be called on
// the process that will use the address
char* MemorySegmentPool::get_address(ObjHandle pointer) {
if (pointer.segmentid() >= segments_.size()) {
open_segment(pointer.segmentid());
}
return static_cast<char*>(segments_[pointer.segmentid()]->get_address_from_handle(pointer.ipcpointer()));
}
MemorySegmentPool::~MemorySegmentPool() {
assert(segment_names_.size() == segments_.size());
for (size_t i = 0; i < segment_names_.size(); ++i) {
segments_[i].reset();
shared_memory_object::remove(segment_names_[i].c_str());
}
}
<commit_msg>opening all memory segments now<commit_after>#include "ipc.h"
ObjHandle::ObjHandle(SegmentId segmentid, size_t size, IpcPointer ipcpointer)
: segmentid_(segmentid), size_(size), ipcpointer_(ipcpointer)
{}
MemorySegmentPool::MemorySegmentPool(bool create) : create_mode_(create) { }
// creates a memory segment if it is not already there; if the pool is in create mode,
// space is allocated, if it is in open mode, the shared memory is mapped into the process
void MemorySegmentPool::open_segment(SegmentId segmentid, size_t size) {
if (segmentid < segments_.size()) {
return;
}
segment_names_.resize(segmentid + 1);
segments_.resize(segmentid + 1);
std::string segment_name = std::string("segment:") + std::to_string(segmentid);
if (create_mode_) {
assert(size > 0);
shared_memory_object::remove(segment_name.c_str()); // remove segment if it has not been properly removed from last run
size_t new_size = (size / page_size_ + 2) * page_size_; // additional room for boost's bookkeeping
segments_[segmentid] = std::unique_ptr<managed_shared_memory>(new managed_shared_memory(create_only, segment_name.c_str(), new_size));
} else {
segments_[segmentid] = std::unique_ptr<managed_shared_memory>(new managed_shared_memory(open_only, segment_name.c_str()));
}
segment_names_[segmentid] = segment_name;
}
ObjHandle MemorySegmentPool::allocate(size_t size) {
// TODO(pcm): at the moment, this always creates a new segment, this will be changed
SegmentId segmentid = segment_names_.size();
open_segment(segmentid, size);
void* ptr = segments_[segmentid]->allocate(size);
auto handle = segments_[segmentid]->get_handle_from_address(ptr);
return ObjHandle(segmentid, size, handle);
}
// returns address of the object refered to by the handle, needs to be called on
// the process that will use the address
char* MemorySegmentPool::get_address(ObjHandle pointer) {
if (pointer.segmentid() >= segments_.size()) {
for (int i = segments_.size(); i <= pointer.segmentid(); ++i) {
open_segment(i);
}
}
managed_shared_memory* segment = segments_[pointer.segmentid()].get();
return static_cast<char*>(segment->get_address_from_handle(pointer.ipcpointer()));
}
MemorySegmentPool::~MemorySegmentPool() {
assert(segment_names_.size() == segments_.size());
for (size_t i = 0; i < segment_names_.size(); ++i) {
segments_[i].reset();
shared_memory_object::remove(segment_names_[i].c_str());
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Fake Frog *
* An Arduino-based project to build a frog-shaped temperature logger. *
* Author: David Lougheed. Copyright 2017. *
******************************************************************************/
#define VERSION "0.1.0"
// Includes
#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal.h>
#include <SD.h>
#include <RTClib.h>
// Compile-Time Settings
#define SERIAL_LOGGING true // Log to the serial display for debug.
#define FILE_LOGGING true // Log to file on SD card. (recommended)
#define DISPLAY_ENABLED true // Show menus and information on an LCD.
#define NUM_SAMPLES 10 // Samples get averaged to reduce noise.
#define SAMPLE_DELAY 10 // Milliseconds between samples.
#define READING_INTERVAL 60 // Seconds between readings.
// Hardware Settings
// - The data logging shield uses A4, A5, and digital pins 10, 11, 12, and 13.
#define NUM_THERMISTORS 4
#define THERMISTOR_1_PIN 0 // Analog pin
#define THERMISTOR_2_PIN 1 // Analog pin
#define THERMISTOR_3_PIN 2 // Analog pin
#define THERMISTOR_4_PIN 3 // Analog pin
const uint8_t thermistor_pins[NUM_THERMISTORS] = {
THERMISTOR_1_PIN,
THERMISTOR_2_PIN,
THERMISTOR_3_PIN,
THERMISTOR_4_PIN
};
#define THERMISTOR_SERIES_RES 10000
#define THERMISTOR_RES_NOM 10000 // Nominal resistance, R0.
#define THERMISTOR_B_COEFF 3950 // Beta coefficient of the thermistor.
#define THERMISTOR_TEMP_NOM 25 // Nominal temperature of R0.
#define BUTTON_1_PIN 2
#define BUTTON_2_PIN 3
#define SD_CARD_PIN 10
#define RTC_PIN_1 A4 // Analog pin
#define RTC_PIN_2 A5 // Analog pin
#define LCD_PIN_RS 4
#define LCD_PIN_EN 5
#define LCD_PIN_DB4 6
#define LCD_PIN_DB5 7
#define LCD_PIN_DB6 8
#define LCD_PIN_DB7 9
#define LCD_ROWS 2
#define LCD_COLUMNS 16
#define RTC_TYPE RTC_PCF8523
// Other Compile-Time Constants
#define MAX_LOG_FILES 1000
#define MAX_DATA_FILES 1000
// Globals
bool serial_logging_started = false;
// - Files
File log_file;
File data_file;
// - Hardware Objects
RTC_TYPE rtc;
LiquidCrystal* lcd;
// - Data Point Variables
// (to save memory, use global data point variables)
DateTime now;
char formatted_timestamp[] = "0000-00-00T00:00:00";
char* data_file_entry_buffer = (char*) malloc(sizeof(char) * 50);
char temperature_string[4][8];
double latest_resistance[4];
double latest_temperature[4];
/*
DISPLAY MODES (ALL WITH LOGGING)
0: Idle
1: Information (RAM free)
2: RTC Editor
*/
uint8_t display_mode = 0;
uint16_t i, z; // 16-bit iterator
uint8_t timer = 0; // Counts seconds
uint32_t milli_timer = 0; // Counts time taken to do a loop
uint32_t uptime = 0;
uint8_t cursor = 0; // Maximum: 31 (second row, last column)
bool button_1 = false;
bool button_2 = false;
// Utility Methods
// Determine amount of free RAM.
// - Retrieved 2017-05-19 (https://playground.arduino.cc/Code/AvailableMemory)
int freeRAM() {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
// Log a generic message.
void log(const char* msg, bool with_newline = true) {
if (SERIAL_LOGGING) {
if(!serial_logging_started) {
Serial.begin(9600);
Serial.println();
serial_logging_started = true;
}
if (with_newline) {
Serial.println(msg);
} else {
Serial.print(msg);
}
}
if (FILE_LOGGING) {
if (log_file) {
if (with_newline) {
log_file.println(msg);
} else {
log_file.print(msg);
}
}
}
}
// Flush various logging buffers.
void log_flush() {
if (SERIAL_LOGGING) {
Serial.flush();
}
if (FILE_LOGGING) {
log_file.flush();
}
}
// Log an error message. Uses standard log method, then hangs forever.
void log_error(const char* msg, bool with_newline = true) {
log(msg, with_newline);
log_flush();
while (true); // Loop forever
}
// Update the LCD to display latest values for the set display mode.
void update_display() {
if (DISPLAY_ENABLED && lcd) {
lcd->clear();
cursor = 0;
switch (display_mode) {
case 1: // Information
lcd->print("Free RAM: ");
lcd->print(freeRAM(), 10);
lcd->noBlink();
break;
case 2: // RTC Editor
lcd->print("TBD");
lcd->setCursor(0, 0);
lcd->blink();
break;
case 0: // Idle
default:
lcd->noBlink();
break;
}
}
}
// Switch the display mode, triggering a display update.
void switch_display_mode(uint8_t m) {
display_mode = m % 3;
update_display();
}
// Data Methods
// Update the global formatted timestamp string with the contents of 'now'.
void update_formatted_timestamp() {
sprintf(formatted_timestamp, "%04u-%02u-%02uT%02u:%02u:%02u", now.year(),
now.month(), now.day(), now.hour(), now.minute(), now.second());
}
double resistance_to_temperature(double resistance) {
// Formula: T = 1/(1/B * ln(R/R_0) + (1/T0)) - 273.15 (celcius)
return 1 / ((log(resistance / THERMISTOR_RES_NOM) / THERMISTOR_B_COEFF) + 1
/ (THERMISTOR_TEMP_NOM + 273.15)) - 273.15;
}
void take_reading(uint8_t t) {
now = rtc.now();
latest_resistance[t] = 0;
for (i = 0; i < NUM_SAMPLES; i++) {
latest_resistance[t] += (double) analogRead(thermistor_pins[t]);
delay(SAMPLE_DELAY);
}
// Formulas: R = sr / (1023 / mean_of_samples - 1)
// sr = thermistor series resistance
latest_resistance[t] = THERMISTOR_SERIES_RES
/ (1023 / (latest_resistance[t] / NUM_SAMPLES) - 1); // Resistance
latest_temperature[t] = resistance_to_temperature(latest_resistance[t]);
// TODO: Error calculations
}
void save_reading_to_card() {
if (data_file) {
update_formatted_timestamp();
for (i = 0; i < NUM_THERMISTORS; i++) {
dtostrf(latest_temperature[i], 5, 2, temperature_string[i]);
}
log("Took reading: ", false);
log(formatted_timestamp, false); log(",", false);
log(temperature_string[0], false); log(",", false);
log(temperature_string[1], false); log(",", false);
log(temperature_string[2], false); log(",", false);
log(temperature_string[3]);
log_flush();
data_file.print(formatted_timestamp); data_file.print(",");
data_file.print(temperature_string[0]); data_file.print(",");
data_file.print(temperature_string[1]); data_file.print(",");
data_file.print(temperature_string[2]); data_file.print(",");
data_file.println(temperature_string[3]);
// data_file.println(data_file_entry_buffer);
data_file.flush();
}
}
// Main Methods
void setup() {
// SET UP EXTERNAL ANALOG VOLTAGE REFERENCE
// Typically from 3.3V Arduino supply. This reduces the voltage noise seen
// from reading analog values.
analogReference(EXTERNAL);
// INITIALIZE SD CARD
log("Initializing SD card... ", false);
pinMode(SD_CARD_PIN, OUTPUT);
if (!SD.begin()) {
log_error("Failed.");
}
log("Done.");
// SET UP LOG FILE
if (FILE_LOGGING) {
log("Creating log file... ", false);
char log_file_name[] = "log_000.txt";
for (i = 0; i < MAX_LOG_FILES; i++) {
// Increment until we can find a log file slot.
// Need to add 48 to get ASCII number characters.
log_file_name[4] = i / 100 + 48;
log_file_name[5] = i / 10 % 10 + 48;
log_file_name[6] = i % 10 + 48;
if (!SD.exists(log_file_name)) {
log_file = SD.open(log_file_name, FILE_WRITE);
break;
}
}
if (log_file) {
log("Done.");
} else {
log_error("Failed.");
}
}
// SET UP RTC
log("Initializing RTC...", false);
Wire.begin();
if (!rtc.begin()) {
log_error("Failed.");
}
log("Done.");
// INPUT RTC TIME
if (SERIAL_LOGGING) {
uint16_t year;
uint8_t month, day, hour, minute, second;
Serial.print("Change clock? (y/n) ");
while (Serial.available() < 1);
if (Serial.read() == 'y') {
Serial.println();
Serial.print("Enter Year: ");
while (Serial.available() < 4);
year += (Serial.read() - 48) * 1000;
year += (Serial.read() - 48) * 100;
year += (Serial.read() - 48) * 10;
year += (Serial.read() - 48);
Serial.println(year);
Serial.print("Enter Month: ");
while (Serial.available() < 2);
month += (Serial.read() - 48) * 10;
month += (Serial.read() - 48);
Serial.println(month);
Serial.print("Enter Day: ");
while (Serial.available() < 2);
day += (Serial.read() - 48) * 10;
day += (Serial.read() - 48);
Serial.println(day);
Serial.print("Enter Hour: ");
while (Serial.available() < 2);
hour += (Serial.read() - 48) * 10;
hour += (Serial.read() - 48);
Serial.println(hour);
Serial.print("Enter Minute: ");
while (Serial.available() < 2);
minute += (Serial.read() - 48) * 10;
minute += (Serial.read() - 48);
Serial.println(minute);
Serial.print("Enter Second: ");
while (Serial.available() < 2);
second += (Serial.read() - 48) * 10;
second += (Serial.read() - 48);
Serial.println(second);
rtc.adjust(DateTime(year, month, day, hour, minute, second));
}
}
// SET UP DATA FILE
log("Creating data file...", false);
char data_file_name[] = "dat_000.csv";
for (i = 0; i < MAX_DATA_FILES; i++) {
// Increment until we can find a data file slot.
// Need to add 48 to get ASCII digit characters.
data_file_name[4] = i / 100 + 48;
data_file_name[5] = i / 10 % 10 + 48;
data_file_name[6] = i % 10 + 48;
if (!SD.exists(data_file_name)) {
data_file = SD.open(data_file_name, FILE_WRITE);
break;
}
}
if (data_file) {
log("Done.");
} else {
log_error("Failed.");
}
// PRINT DATA FILE CSV HEADERS
data_file.println("Timestamp,Temp1,Temp2,Temp3,Temp4");
data_file.flush();
// SET UP LCD
if (DISPLAY_ENABLED) {
lcd = new LiquidCrystal(LCD_PIN_RS, LCD_PIN_EN, LCD_PIN_DB4,
LCD_PIN_DB5, LCD_PIN_DB6, LCD_PIN_DB7);
lcd->begin(LCD_COLUMNS, LCD_ROWS);
update_display();
}
// SET UP BUTTONS
pinMode(BUTTON_1_PIN, INPUT);
pinMode(BUTTON_2_PIN, INPUT);
// Finished everything!
now = rtc.now();
update_formatted_timestamp();
log("Data logger started at ", false);
log(formatted_timestamp, false);
log(". Software version: ", false);
log(VERSION);
log_flush();
}
void loop() {
// Time the loop to make sure it runs rounded to the nearest second.
milli_timer = millis();
if (timer >= READING_INTERVAL) {
timer = 0;
for (z = 0; z < NUM_THERMISTORS; z++) { // Loop through all thermistors
take_reading(z);
}
save_reading_to_card();
}
button_1 = digitalRead(BUTTON_1_PIN);
button_2 = digitalRead(BUTTON_2_PIN);
if (button_1 && button_2) {
switch_display_mode(++display_mode);
} else if (button_1) {
} else if (button_2) {
cursor = (cursor + 1) % 32;
lcd->setCursor(cursor % 16, cursor > 15 ? 1 : 0);
}
milli_timer = millis() - milli_timer;
while (milli_timer >= 1000) {
// Prevent an integer overflow error by making sure milli_timer < 1000
timer++; // An extra second has occurred - don't let it slip away!
milli_timer -= 1000;
}
timer++;
uptime++;
delay(1000 - milli_timer); // (Ideally) 1 second between loops
}
<commit_msg>Fix small text formatting issues<commit_after>/******************************************************************************
* Fake Frog *
* An Arduino-based project to build a frog-shaped temperature logger. *
* Author: David Lougheed. Copyright 2017. *
******************************************************************************/
#define VERSION "0.1.0"
// Includes
#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal.h>
#include <SD.h>
#include <RTClib.h>
// Compile-Time Settings
#define SERIAL_LOGGING true // Log to the serial display for debug.
#define FILE_LOGGING true // Log to file on SD card. (recommended)
#define DISPLAY_ENABLED true // Show menus and information on an LCD.
#define NUM_SAMPLES 10 // Samples get averaged to reduce noise.
#define SAMPLE_DELAY 10 // Milliseconds between samples.
#define READING_INTERVAL 60 // Seconds between readings.
// Hardware Settings
// - The data logging shield uses A4, A5, and digital pins 10, 11, 12, and 13.
#define NUM_THERMISTORS 4
#define THERMISTOR_1_PIN 0 // Analog pin
#define THERMISTOR_2_PIN 1 // Analog pin
#define THERMISTOR_3_PIN 2 // Analog pin
#define THERMISTOR_4_PIN 3 // Analog pin
const uint8_t thermistor_pins[NUM_THERMISTORS] = {
THERMISTOR_1_PIN,
THERMISTOR_2_PIN,
THERMISTOR_3_PIN,
THERMISTOR_4_PIN
};
#define THERMISTOR_SERIES_RES 10000
#define THERMISTOR_RES_NOM 10000 // Nominal resistance, R0.
#define THERMISTOR_B_COEFF 3950 // Beta coefficient of the thermistor.
#define THERMISTOR_TEMP_NOM 25 // Nominal temperature of R0.
#define BUTTON_1_PIN 2
#define BUTTON_2_PIN 3
#define SD_CARD_PIN 10
#define RTC_PIN_1 A4 // Analog pin
#define RTC_PIN_2 A5 // Analog pin
#define LCD_PIN_RS 4
#define LCD_PIN_EN 5
#define LCD_PIN_DB4 6
#define LCD_PIN_DB5 7
#define LCD_PIN_DB6 8
#define LCD_PIN_DB7 9
#define LCD_ROWS 2
#define LCD_COLUMNS 16
#define RTC_TYPE RTC_PCF8523
// Other Compile-Time Constants
#define MAX_LOG_FILES 1000
#define MAX_DATA_FILES 1000
// Globals
bool serial_logging_started = false;
// - Files
File log_file;
File data_file;
// - Hardware Objects
RTC_TYPE rtc;
LiquidCrystal* lcd;
// - Data Point Variables
// (to save memory, use global data point variables)
DateTime now;
char formatted_timestamp[] = "0000-00-00T00:00:00";
char* data_file_entry_buffer = (char*) malloc(sizeof(char) * 50);
char temperature_string[4][8];
double latest_resistance[4];
double latest_temperature[4];
/*
DISPLAY MODES (ALL WITH LOGGING)
0: Idle
1: Information (RAM free)
2: RTC Editor
*/
uint8_t display_mode = 0;
uint16_t i, z; // 16-bit iterator
uint8_t timer = 0; // Counts seconds
uint32_t milli_timer = 0; // Counts time taken to do a loop
uint32_t uptime = 0;
uint8_t cursor = 0; // Maximum: 31 (second row, last column)
bool button_1 = false;
bool button_2 = false;
// Utility Methods
// Determine amount of free RAM.
// - Retrieved 2017-05-19 (https://playground.arduino.cc/Code/AvailableMemory)
int freeRAM() {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
// Log a generic message.
void log(const char* msg, bool with_newline = true) {
if (SERIAL_LOGGING) {
if(!serial_logging_started) {
Serial.begin(9600);
Serial.println();
serial_logging_started = true;
}
if (with_newline) {
Serial.println(msg);
} else {
Serial.print(msg);
}
}
if (FILE_LOGGING) {
if (log_file) {
if (with_newline) {
log_file.println(msg);
} else {
log_file.print(msg);
}
}
}
}
// Flush various logging buffers.
void log_flush() {
if (SERIAL_LOGGING) {
Serial.flush();
}
if (FILE_LOGGING) {
log_file.flush();
}
}
// Log an error message. Uses standard log method, then hangs forever.
void log_error(const char* msg, bool with_newline = true) {
log(msg, with_newline);
log_flush();
while (true); // Loop forever
}
// Update the LCD to display latest values for the set display mode.
void update_display() {
if (DISPLAY_ENABLED && lcd) {
lcd->clear();
cursor = 0;
switch (display_mode) {
case 1: // Information
lcd->print("Free RAM: ");
lcd->print(freeRAM(), 10);
lcd->noBlink();
break;
case 2: // RTC Editor
lcd->print("TBD");
lcd->setCursor(0, 0);
lcd->blink();
break;
case 0: // Idle
default:
lcd->noBlink();
break;
}
}
}
// Switch the display mode, triggering a display update.
void switch_display_mode(uint8_t m) {
display_mode = m % 3;
update_display();
}
// Data Methods
// Update the global formatted timestamp string with the contents of 'now'.
void update_formatted_timestamp() {
sprintf(formatted_timestamp, "%04u-%02u-%02uT%02u:%02u:%02u", now.year(),
now.month(), now.day(), now.hour(), now.minute(), now.second());
}
double resistance_to_temperature(double resistance) {
// Formula: T = 1/(1/B * ln(R/R_0) + (1/T0)) - 273.15 (celcius)
return 1 / ((log(resistance / THERMISTOR_RES_NOM) / THERMISTOR_B_COEFF) + 1
/ (THERMISTOR_TEMP_NOM + 273.15)) - 273.15;
}
void take_reading(uint8_t t) {
now = rtc.now();
latest_resistance[t] = 0;
for (i = 0; i < NUM_SAMPLES; i++) {
latest_resistance[t] += (double) analogRead(thermistor_pins[t]);
delay(SAMPLE_DELAY);
}
// Formulas: R = sr / (1023 / mean_of_samples - 1)
// sr = thermistor series resistance
latest_resistance[t] = THERMISTOR_SERIES_RES
/ (1023 / (latest_resistance[t] / NUM_SAMPLES) - 1); // Resistance
latest_temperature[t] = resistance_to_temperature(latest_resistance[t]);
// TODO: Error calculations
}
void save_reading_to_card() {
if (data_file) {
update_formatted_timestamp();
for (i = 0; i < NUM_THERMISTORS; i++) {
dtostrf(latest_temperature[i], 5, 2, temperature_string[i]);
}
log("Took reading: ", false);
log(formatted_timestamp, false); log(",", false);
log(temperature_string[0], false); log(",", false);
log(temperature_string[1], false); log(",", false);
log(temperature_string[2], false); log(",", false);
log(temperature_string[3]);
log_flush();
data_file.print(formatted_timestamp); data_file.print(",");
data_file.print(temperature_string[0]); data_file.print(",");
data_file.print(temperature_string[1]); data_file.print(",");
data_file.print(temperature_string[2]); data_file.print(",");
data_file.println(temperature_string[3]);
// data_file.println(data_file_entry_buffer);
data_file.flush();
}
}
// Main Methods
void setup() {
// SET UP EXTERNAL ANALOG VOLTAGE REFERENCE
// Typically from 3.3V Arduino supply. This reduces the voltage noise seen
// from reading analog values.
analogReference(EXTERNAL);
// INITIALIZE SD CARD
log("Initializing SD card... ", false);
pinMode(SD_CARD_PIN, OUTPUT);
if (!SD.begin()) {
log_error("Failed.");
}
log("Done.");
// SET UP LOG FILE
if (FILE_LOGGING) {
log("Creating log file... ", false);
char log_file_name[] = "log_000.txt";
for (i = 0; i < MAX_LOG_FILES; i++) {
// Increment until we can find a log file slot.
// Need to add 48 to get ASCII number characters.
log_file_name[4] = i / 100 + 48;
log_file_name[5] = i / 10 % 10 + 48;
log_file_name[6] = i % 10 + 48;
if (!SD.exists(log_file_name)) {
log_file = SD.open(log_file_name, FILE_WRITE);
break;
}
}
if (log_file) {
log("Done.");
} else {
log_error("Failed.");
}
}
// SET UP RTC
log("Initializing RTC... ", false);
Wire.begin();
if (!rtc.begin()) {
log_error("Failed.");
}
log("Done.");
// INPUT RTC TIME
if (SERIAL_LOGGING) {
uint16_t year;
uint8_t month, day, hour, minute, second;
Serial.print("Change clock? (y/n) ");
while (Serial.available() < 1);
Serial.println();
if (Serial.read() == 'y') {
Serial.println();
Serial.print("Enter Year: ");
while (Serial.available() < 4);
year += (Serial.read() - 48) * 1000;
year += (Serial.read() - 48) * 100;
year += (Serial.read() - 48) * 10;
year += (Serial.read() - 48);
Serial.println(year);
Serial.print("Enter Month: ");
while (Serial.available() < 2);
month += (Serial.read() - 48) * 10;
month += (Serial.read() - 48);
Serial.println(month);
Serial.print("Enter Day: ");
while (Serial.available() < 2);
day += (Serial.read() - 48) * 10;
day += (Serial.read() - 48);
Serial.println(day);
Serial.print("Enter Hour: ");
while (Serial.available() < 2);
hour += (Serial.read() - 48) * 10;
hour += (Serial.read() - 48);
Serial.println(hour);
Serial.print("Enter Minute: ");
while (Serial.available() < 2);
minute += (Serial.read() - 48) * 10;
minute += (Serial.read() - 48);
Serial.println(minute);
Serial.print("Enter Second: ");
while (Serial.available() < 2);
second += (Serial.read() - 48) * 10;
second += (Serial.read() - 48);
Serial.println(second);
rtc.adjust(DateTime(year, month, day, hour, minute, second));
}
}
// SET UP DATA FILE
log("Creating data file... ", false);
char data_file_name[] = "dat_000.csv";
for (i = 0; i < MAX_DATA_FILES; i++) {
// Increment until we can find a data file slot.
// Need to add 48 to get ASCII digit characters.
data_file_name[4] = i / 100 + 48;
data_file_name[5] = i / 10 % 10 + 48;
data_file_name[6] = i % 10 + 48;
if (!SD.exists(data_file_name)) {
data_file = SD.open(data_file_name, FILE_WRITE);
break;
}
}
if (data_file) {
log("Done.");
} else {
log_error("Failed.");
}
// PRINT DATA FILE CSV HEADERS
data_file.println("Timestamp,Temp1,Temp2,Temp3,Temp4");
data_file.flush();
// SET UP LCD
if (DISPLAY_ENABLED) {
lcd = new LiquidCrystal(LCD_PIN_RS, LCD_PIN_EN, LCD_PIN_DB4,
LCD_PIN_DB5, LCD_PIN_DB6, LCD_PIN_DB7);
lcd->begin(LCD_COLUMNS, LCD_ROWS);
update_display();
}
// SET UP BUTTONS
pinMode(BUTTON_1_PIN, INPUT);
pinMode(BUTTON_2_PIN, INPUT);
// Finished everything!
now = rtc.now();
update_formatted_timestamp();
log("Data logger started at ", false);
log(formatted_timestamp, false);
log(". Software version: ", false);
log(VERSION);
log_flush();
}
void loop() {
// Time the loop to make sure it runs rounded to the nearest second.
milli_timer = millis();
if (timer >= READING_INTERVAL) {
timer = 0;
for (z = 0; z < NUM_THERMISTORS; z++) { // Loop through all thermistors
take_reading(z);
}
save_reading_to_card();
}
button_1 = digitalRead(BUTTON_1_PIN);
button_2 = digitalRead(BUTTON_2_PIN);
if (button_1 && button_2) {
switch_display_mode(++display_mode);
} else if (button_1) {
} else if (button_2) {
cursor = (cursor + 1) % 32;
lcd->setCursor(cursor % 16, cursor > 15 ? 1 : 0);
}
milli_timer = millis() - milli_timer;
while (milli_timer >= 1000) {
// Prevent an integer overflow error by making sure milli_timer < 1000
timer++; // An extra second has occurred - don't let it slip away!
milli_timer -= 1000;
}
timer++;
uptime++;
delay(1000 - milli_timer); // (Ideally) 1 second between loops
}
<|endoftext|> |
<commit_before><commit_msg>edited main.cpp<commit_after>#include "../headerse/parser.h"
#include <stdio.h>
#include <unistd.h>
#include <iostream>
using namespace std;
int main()
{
//get host name and user id
string cmd;
string user_id;
bool prev_cmd = true;
char hostname[100];
//FIXME:instantiate object of type parse
if (getlogin() == NULL)
{
user_id = "";
perror("ERROR: could not log in");
}
else
{
user_id = getlogin();
}
if (gethostname(hostname, 100) == -1)
{
perror("ERROR: could not get host name");
}
while (1)
{
//print out hostname and user id
if (getlogin() != NULL)
{
cout << "[" << user_id << "@" << hostname << "]";
}
cout << "$ ";
//get user input
getline(cin,cmd);
//FIXME: need a line of code for parsing here
}
return 0;
}
<|endoftext|> |
<commit_before>/*
Original code from tekkies/CVdrone (get actual address from github)
Modified by Elliot Greenlee, Caleb Mennen, Jacob Pollack
COSC 402 Senior Design
Min Kao Drone Tour
See readme at (get actual address from github)
*/
#include "ardrone/ardrone.h"
#include "structures.h"
#include "manual/manual.h"
#include "objectFollowing/objectFollowing.h"
#include "lineFollowing/lineFollowing.h"
#include <iostream>
#include <vector>
#include <chrono>
#include <thread>
#include <string>
using namespace std;
class Control {
public:
const string flightLog = "flight_log.txt";
//AR.Drone class
ARDrone ardrone;
cv::Mat image;
int key;
FlyingMode flyingMode = Manual;
double speed = 0.0;
int batteryPercentage;
bool flying;
ControlMovements velocities;
FILE *flight_log;
void initializeDroneControl(ObjectFollowing *objectFollowing);
void detectFlyingMode();
bool detectEscape();
void changeSpeed();
void getImage();
void overlayControl();
};
/*
*/
void Control::initializeDroneControl(ObjectFollowing *objectFollowing) {
//Initializing Message
printf("Connecting to the drone\n");
printf("If there is no version number response in the next 10 seconds, please restart the drone and code.\n");
fflush(stdout);
// Initialize
if (!ardrone.open()) {
printf("Failed to initialize.\n");
//TODO: fix this return -1;
}
//Set drone on flat surface and initialize
ardrone.setFlatTrim();
//initialize object following code
objectFollowing->initializeObjectFollowing();
flight_log = fopen(flightLog.c_str(), "w");
//Print default command information
printf("To disconnect, press the ESC key\n\n");
printf("Currently the drone is in manual mode.\n");
printf("Use the b key for manual mode, the n key for object following, and the m key for line following. The number keys can be used to set a speed. Use spacebar to take off and land, which is required before any control can be executed.\n\n");
}
/*
Detect ESC key press and
*/
bool Control::detectEscape() {
//Escape key
if (key == 0x1b) { return true; }
return false;
}
/*
*/
void Control::changeSpeed() {
if ((key >= '0') && (key <= '9')) //number keys
{
speed = (key-'0')*0.1;
}
}
/*
*/
void Control::getImage() {
//Get an image
image = ardrone.getImage();
}
/*
Switch between flying modes
*/
void Control::detectFlyingMode() {
if (key == 'b') {
flyingMode = Manual;
ardrone.setCamera(0);
printf("Manual flying mode is enabled\n");
printf("Press n for object following and m for line following\n");
printf("While in manual mode, use q and a for up and down, t and g for forward and backward, and f and h for left and right. Press space to take off.\n\n");
}
else if (key == 'n') {
flyingMode = ObjectFollow;
ardrone.setCamera(0);
printf("Object Following flying mode is enabled\n");
printf("Press b for manual and m for line following\n");
printf("While in object following mode, use l to toggle learning a specific color. Press space to take off after learning a color.\n\n");
}
else if (key == 'm') {
flyingMode = LineFollow;
ardrone.setCamera(1);
printf("Line Following flying mode is enabled\n");
printf("Press b for manual and n for object following\n");
printf("No control for line following yet exists\n\n");
}
}
void Control::overlayControl() {
//TODO: move this so it isnt called every time
cv::Scalar green = CV_RGB(0,255,0); //putText color value
char modeDisplay[80]; //print buffer for flying mode
char speedDisplay[80]; //print buffer for speed
if (flyingMode == Manual) {
sprintf(modeDisplay, "Manual Mode");
}
else if (flyingMode == ObjectFollow) {
sprintf(modeDisplay, "Object Following Mode");
}
else if (flyingMode == LineFollow) {
sprintf(modeDisplay, "Line Following Mode");
}
sprintf(speedDisplay, "Speed = %3.2f", speed);
//add speed to overlay
putText(image, speedDisplay, cvPoint(30,40), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);
//add flying mode to overlay
putText(image, modeDisplay, cvPoint(30,20), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);
cv::imshow("camera", image); //Display the camera feed
}
int main(int argc, char *argv[])
{
Control control;
//Controlling classes
ObjectFollowing objectFollowing;
//TODO: ManualDriving manualDriving;
//TODO: LineFollowing lineFollwing;
//Display variables
char flyingDisplay[80]; //print buffer for if flying
cv::Scalar green = CV_RGB(0,255,0); //putText color value
line_main();
control.initializeDroneControl(&objectFollowing);
// Main loop
while (1) {
control.key = cv::waitKey(33); // Key input
if (control.detectEscape()) { break; } //Press ESC to close program
control.detectFlyingMode(); //Press b, n, m to change mode
control.changeSpeed(); //Press 0-9 to change speed
control.getImage(); //get the image from the camera
//Take off / Landing
if (control.key == ' ') { //spacebar
if (control.ardrone.onGround()) {
control.ardrone.takeoff();
fprintf(control.flight_log, "TAKEOFF\n");
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
}
else {
control.ardrone.landing();
fprintf(control.flight_log, "LAND\n");
}
}
//TODO:Write battery percentage to screen
printf("%d\n", control.ardrone.getBatteryPercentage());
//Write if grounded or flying to image
if (control.ardrone.onGround()) {
sprintf(flyingDisplay, "Landed");
}
else {
sprintf(flyingDisplay, "Flying");
}
putText(control.image, flyingDisplay, cvPoint(200,40), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);
switch (control.flyingMode) {
case Manual:
//TODO: Allow user to set camera mode in Manual
//TODO: Change 0/1 to CONSTANTS of 0 = front, 1 = bottom
//TODO: Scale these values for normal human control when in manual mode
control.velocities = manualMovement(control.key);
//TODO: Move this into manualMovement(control.key) function
displayManualInfo(&(control.image), control.velocities);
break;
case ObjectFollow:
control.velocities = objectFollowing.detectObject(control.image, control.key);
break;
case LineFollow:
//TODO implement for real
control.velocities = lineFollowingControl();
break;
}
control.overlayControl();
control.ardrone.move3D(control.velocities.vx * control.speed, control.velocities.vy * control.speed, control.velocities.vz * control.speed, control.velocities.vr);
}
//Write hsv values to a file
objectFollowing.closeObjectFollowing();
//TODO: closeManual();
//TODO: closeLineFollowing();
//Close connection to drone
control.ardrone.close();
return 0;
}
<commit_msg>testing<commit_after>/*
Original code from tekkies/CVdrone (get actual address from github)
Modified by Elliot Greenlee, Caleb Mennen, Jacob Pollack
COSC 402 Senior Design
Min Kao Drone Tour
See readme at (get actual address from github)
*/
#include "ardrone/ardrone.h"
#include "structures.h"
#include "manual/manual.h"
#include "objectFollowing/objectFollowing.h"
#include "lineFollowing/lineFollowing.h"
#include <iostream>
#include <vector>
#include <chrono>
#include <thread>
#include <string>
using namespace std;
class Control {
public:
const string flightLog = "flight_log.txt";
//AR.Drone class
ARDrone ardrone;
cv::Mat image;
int key;
FlyingMode flyingMode = Manual;
double speed = 0.0;
int batteryPercentage;
bool flying;
ControlMovements velocities;
FILE *flight_log;
void initializeDroneControl(ObjectFollowing *objectFollowing);
void detectFlyingMode();
bool detectEscape();
void changeSpeed();
void getImage();
void overlayControl();
};
/*
*/
void Control::initializeDroneControl(ObjectFollowing *objectFollowing) {
//Initializing Message
printf("Connecting to the drone\n");
printf("If there is no version number response in the next 10 seconds, please restart the drone and code.\n");
fflush(stdout);
// Initialize
if (!ardrone.open()) {
printf("Failed to initialize.\n");
//TODO: fix this return -1;
}
//Set drone on flat surface and initialize
ardrone.setFlatTrim();
//initialize object following code
objectFollowing->initializeObjectFollowing();
flight_log = fopen(flightLog.c_str(), "w");
//Print default command information
printf("To disconnect, press the ESC key\n\n");
printf("Currently the drone is in manual mode.\n");
printf("Use the b key for manual mode, the n key for object following, and the m key for line following. The number keys can be used to set a speed. Use spacebar to take off and land, which is required before any control can be executed.\n\n");
}
/*
Detect ESC key press and
*/
bool Control::detectEscape() {
//Escape key
if (key == 0x1b) { return true; }
return false;
}
/*
*/
void Control::changeSpeed() {
if ((key >= '0') && (key <= '9')) //number keys
{
speed = (key-'0')*0.1;
}
}
/*
*/
void Control::getImage() {
//Get an image
image = ardrone.getImage();
}
/*
Switch between flying modes
*/
void Control::detectFlyingMode() {
if (key == 'b') {
flyingMode = Manual;
ardrone.setCamera(0);
printf("Manual flying mode is enabled\n");
printf("Press n for object following and m for line following\n");
printf("While in manual mode, use q and a for up and down, t and g for forward and backward, and f and h for left and right. Press space to take off.\n\n");
}
else if (key == 'n') {
flyingMode = ObjectFollow;
ardrone.setCamera(0);
printf("Object Following flying mode is enabled\n");
printf("Press b for manual and m for line following\n");
printf("While in object following mode, use l to toggle learning a specific color. Press space to take off after learning a color.\n\n");
}
else if (key == 'm') {
flyingMode = LineFollow;
ardrone.setCamera(1);
printf("Line Following flying mode is enabled\n");
printf("Press b for manual and n for object following\n");
printf("No control for line following yet exists\n\n");
}
}
void Control::overlayControl() {
//TODO: move this so it isnt called every time
cv::Scalar green = CV_RGB(0,255,0); //putText color value
char modeDisplay[80]; //print buffer for flying mode
char speedDisplay[80]; //print buffer for speed
if (flyingMode == Manual) {
sprintf(modeDisplay, "Manual Mode");
}
else if (flyingMode == ObjectFollow) {
sprintf(modeDisplay, "Object Following Mode");
}
else if (flyingMode == LineFollow) {
sprintf(modeDisplay, "Line Following Mode");
}
sprintf(speedDisplay, "Speed = %3.2f", speed);
//add speed to overlay
putText(image, speedDisplay, cvPoint(30,40), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);
//add flying mode to overlay
putText(image, modeDisplay, cvPoint(30,20), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);
cv::imshow("camera", image); //Display the camera feed
}
int main(int argc, char *argv[])
{
Control control;
//Controlling classes
ObjectFollowing objectFollowing;
//TODO: ManualDriving manualDriving;
//TODO: LineFollowing lineFollwing;
//Display variables
char flyingDisplay[80]; //print buffer for if flying
cv::Scalar green = CV_RGB(0,255,0); //putText color value
line_main();
return 1;
control.initializeDroneControl(&objectFollowing);
// Main loop
while (1) {
control.key = cv::waitKey(33); // Key input
if (control.detectEscape()) { break; } //Press ESC to close program
control.detectFlyingMode(); //Press b, n, m to change mode
control.changeSpeed(); //Press 0-9 to change speed
control.getImage(); //get the image from the camera
//Take off / Landing
if (control.key == ' ') { //spacebar
if (control.ardrone.onGround()) {
control.ardrone.takeoff();
fprintf(control.flight_log, "TAKEOFF\n");
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
}
else {
control.ardrone.landing();
fprintf(control.flight_log, "LAND\n");
}
}
//TODO:Write battery percentage to screen
printf("%d\n", control.ardrone.getBatteryPercentage());
//Write if grounded or flying to image
if (control.ardrone.onGround()) {
sprintf(flyingDisplay, "Landed");
}
else {
sprintf(flyingDisplay, "Flying");
}
putText(control.image, flyingDisplay, cvPoint(200,40), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);
switch (control.flyingMode) {
case Manual:
//TODO: Allow user to set camera mode in Manual
//TODO: Change 0/1 to CONSTANTS of 0 = front, 1 = bottom
//TODO: Scale these values for normal human control when in manual mode
control.velocities = manualMovement(control.key);
//TODO: Move this into manualMovement(control.key) function
displayManualInfo(&(control.image), control.velocities);
break;
case ObjectFollow:
control.velocities = objectFollowing.detectObject(control.image, control.key);
break;
case LineFollow:
//TODO implement for real
control.velocities = lineFollowingControl();
break;
}
control.overlayControl();
control.ardrone.move3D(control.velocities.vx * control.speed, control.velocities.vy * control.speed, control.velocities.vz * control.speed, control.velocities.vr);
}
//Write hsv values to a file
objectFollowing.closeObjectFollowing();
//TODO: closeManual();
//TODO: closeLineFollowing();
//Close connection to drone
control.ardrone.close();
return 0;
}
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; version 3 of the License.
*
* 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.
*/
#include <QtGui/QApplication>
#include "config.h"
#include "dbmanager.h"
#include "iconmanager.h"
#include "mainwindow.h"
#include "plugins/pluginmanager.h"
#include "sqlhighlighter.h"
#include "tabwidget/abstracttabwidget.h"
#include "widgets/querytextedit.h"
int main(int argc, char *argv[])
{
QApplication::setApplicationName("dbmaster");
QApplication::setApplicationVersion("0.8");
QApplication::setOrganizationDomain("dbmaster.org");
QApplication a(argc, argv);
QSplashScreen splash(QPixmap(":/img/splash.png"));
splash.show();
// Loading translations
splash.showMessage(QObject::tr("Loading translations..."), Qt::AlignBottom);
QTranslator translator;
// getting the current locale
QString lang = QLocale::system().name();
QString transdir;
#if defined(Q_WS_X11)
// for *nix
transdir = QString(PREFIX).append("/share/dbmaster/tr");
#endif
#if defined(Q_WS_WIN)
transdir = "share/tr";
#endif
QString path;
/* on teste d'abord si le .qm est dans le dossier courant -> alors on est en
* dev, on le charge, sinon il est dans le répertoire d'installation. */
path = QDir::currentPath() + QString("/../tr/%1.qm").arg(lang);
if (!QFile::exists(path))
path = transdir.append("/%1.qm").arg(lang);
translator.load(path);
a.installTranslator(&translator);
QTranslator qtTranslator;
qtTranslator.load("qt_" + lang,
#if defined (Q_WS_X11)
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
#endif
#if defined (Q_WS_WIN)
QDir::currentPath());
#endif
a.installTranslator(&qtTranslator);
// Ajout des plugins
splash.showMessage(QObject::tr("Loading plugins..."), Qt::AlignBottom);
PluginManager::init();
splash.showMessage(QObject::tr("Initialization..."), Qt::AlignBottom);
IconManager::init();
DbManager::init();
Config::init();
QueryTextEdit::reloadCompleter();
MainWindow *w = new MainWindow();
w->show();
splash.finish(w);
if (a.arguments().size() >= 2) {
for (int i=1; i<a.arguments().size(); i++) {
w->openQuery(a.arguments()[i]);
}
}
return a.exec();
}
<commit_msg>Num version<commit_after>/*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; version 3 of the License.
*
* 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.
*/
#include <QtGui/QApplication>
#include "config.h"
#include "dbmanager.h"
#include "iconmanager.h"
#include "mainwindow.h"
#include "plugins/pluginmanager.h"
#include "sqlhighlighter.h"
#include "tabwidget/abstracttabwidget.h"
#include "widgets/querytextedit.h"
int main(int argc, char *argv[]) {
QApplication::setApplicationName("dbmaster");
QApplication::setApplicationVersion("0.8.1");
QApplication::setOrganizationDomain("dbmaster.org");
QApplication a(argc, argv);
QSplashScreen splash(QPixmap(":/img/splash.png"));
splash.show();
// Loading translations
splash.showMessage(QObject::tr("Loading translations..."), Qt::AlignBottom);
QTranslator translator;
// getting the current locale
QString lang = QLocale::system().name();
QString transdir;
#if defined(Q_WS_X11)
// for *nix
transdir = QString(PREFIX).append("/share/dbmaster/tr");
#endif
#if defined(Q_WS_WIN)
transdir = "share/tr";
#endif
QString path;
/* on teste d'abord si le .qm est dans le dossier courant -> alors on est en
* dev, on le charge, sinon il est dans le répertoire d'installation. */
path = QDir::currentPath() + QString("/../tr/%1.qm").arg(lang);
if (!QFile::exists(path))
path = transdir.append("/%1.qm").arg(lang);
translator.load(path);
a.installTranslator(&translator);
QTranslator qtTranslator;
qtTranslator.load("qt_" + lang,
#if defined (Q_WS_X11)
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
#endif
#if defined (Q_WS_WIN)
QDir::currentPath());
#endif
a.installTranslator(&qtTranslator);
// Ajout des plugins
splash.showMessage(QObject::tr("Loading plugins..."), Qt::AlignBottom);
PluginManager::init();
splash.showMessage(QObject::tr("Initialization..."), Qt::AlignBottom);
IconManager::init();
DbManager::init();
Config::init();
QueryTextEdit::reloadCompleter();
MainWindow *w = new MainWindow();
w->show();
splash.finish(w);
if (a.arguments().size() >= 2) {
for (int i=1; i<a.arguments().size(); i++) {
w->openQuery(a.arguments()[i]);
}
}
return a.exec();
}
<|endoftext|> |
<commit_before>#include <Arduino.h>
#include <avr/wdt.h>
#include <TinyGPS++.h>
#include <idDHT11.h>
#include <SDCard.h>
#include <Utils.h>
#include <PinMap.h>
#ifdef DEBUG
#include <MemoryFree.h>
#include <SoftwareSerial.h>
SoftwareSerial gpsSerial(8, 9);
#endif
SDCard sd(SD_PIN);
TinyGPSPlus gps;
Utils utils;
bool firstEntry = true;
char fileName [11];
int ledState = LOW;
/**
* initialize dht as on library documentation
* @see https://github.com/niesteszeck/idDHT11/blob/master/examples/idDHT11_Lib_example/idDHT11_Lib_example.ino
* @see https://www.arduino.cc/en/Reference/AttachInterrupt
*/
void dht11_wrapper();
idDHT11 dht(DHT_PIN, 1, dht11_wrapper);
void dht11_wrapper() {
dht.isrCallback();
}
/**
* wrap all data together to be appended to csv log file
*/
void serialize(char* entry) {
while(dht.acquiring());
int result = dht.getStatus();
if (result != IDDHTLIB_OK) {
#ifdef DEBUG
dht.printError(result);
#endif
} else {
// save new values
dht.saveLastValidData();
}
sprintf(
entry,
"%i,%i,%i,%i,%0.2f,%0.2f,%0.2f",
utils.readMQ(MQ2_PIN), utils.readMQ(MQ135_PIN),
(int)dht.getLastValidCelsius(), (int)dht.getLastValidHumidity(),
gps.location.lat(), gps.location.lng(), gps.altitude.meters()
);
}
void createFileName(char *str) {
// limited to 8.3 file format https://en.wikipedia.org/wiki/8.3_filename
// so .csv was removed
sprintf(str, "%d-%d-%d", gps.date.day(), gps.time.hour(), gps.time.minute());
}
/**
* delay while keep reading gps data
*/
void smartDelay(const unsigned long &delay) {
unsigned long initialTime = millis();
unsigned long currentTime;
do {
#ifdef DEBUG
if (gpsSerial.available() > 0) {
gps.encode(gpsSerial.read());
#else
if (Serial.available() > 0) {
gps.encode(Serial.read());
#endif
}
currentTime = millis();
} while (currentTime - initialTime < delay);
}
void setup() {
Serial.begin(9600);
#ifdef DEBUG
Serial.println(F("setup: initializing sensor platform..."));
gpsSerial.begin(9600);
#endif
// setup control led
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
// enable watchdog with 2 seconds timer
wdt_enable(WDTO_2S);
if(!sd.begin()) {
utils.error("setup: sd could not begin!");
}
// start acquiring first value, result is interrupt driven
// the dht sensor is having issues since the soldering on the board,
// this is a tmeporary work around to get valid values
if (dht.acquireAndWait() != IDDHTLIB_OK) {
utils.error("setup: dht could not acquire proper data!");
} else {
dht.saveLastValidData();
}
#ifdef DEBUG
Serial.println(F("setup: initialization went okay!"));
#endif
}
void loop() {
smartDelay(255);
if (firstEntry && gps.date.isValid() && gps.location.isValid()) {
// if valid state is entered, led is on
digitalWrite(LED_PIN, HIGH);
createFileName(fileName);
if (sd.exists(fileName)) {
#ifdef DEBUG
Serial.print(F("appending to file "));
Serial.println(fileName);
#endif
firstEntry = false;
} else {
#ifdef DEBUG
Serial.print(F("new log file "));
Serial.println(fileName);
#endif
firstEntry = false;
}
}
if (!firstEntry && gps.location.isValid()) {
// if valid state is entered, led is on
digitalWrite(LED_PIN, HIGH);
if (gps.location.isUpdated()) {
// get new dht value
dht.acquire();
char entry [40];
serialize(entry);
#ifdef DEBUG
Serial.println(entry);
#endif
if (!sd.writeToFile(fileName, entry)) {
utils.error("could not write data to file");
}
}
} else {
// blink for invalid gps data
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(LED_PIN, ledState);
}
// reset watchdog timer
wdt_reset();
}
<commit_msg>add more precision to lat/lon<commit_after>#include <Arduino.h>
#include <avr/wdt.h>
#include <TinyGPS++.h>
#include <idDHT11.h>
#include <SDCard.h>
#include <Utils.h>
#include <PinMap.h>
#ifdef DEBUG
#include <MemoryFree.h>
#include <SoftwareSerial.h>
SoftwareSerial gpsSerial(8, 9);
#endif
SDCard sd(SD_PIN);
TinyGPSPlus gps;
Utils utils;
bool firstEntry = true;
char fileName [11];
int ledState = LOW;
/**
* initialize dht as on library documentation
* @see https://github.com/niesteszeck/idDHT11/blob/master/examples/idDHT11_Lib_example/idDHT11_Lib_example.ino
* @see https://www.arduino.cc/en/Reference/AttachInterrupt
*/
void dht11_wrapper();
idDHT11 dht(DHT_PIN, 1, dht11_wrapper);
void dht11_wrapper() {
dht.isrCallback();
}
/**
* wrap all data together to be appended to csv log file
*/
void serialize(char* entry) {
while(dht.acquiring());
int result = dht.getStatus();
if (result != IDDHTLIB_OK) {
#ifdef DEBUG
dht.printError(result);
#endif
} else {
// save new values
dht.saveLastValidData();
}
sprintf(
entry,
"%i,%i,%i,%i,%0.6f,%0.6f,%0.2f",
utils.readMQ(MQ2_PIN), utils.readMQ(MQ135_PIN),
(int)dht.getLastValidCelsius(), (int)dht.getLastValidHumidity(),
gps.location.lat(), gps.location.lng(), gps.altitude.meters()
);
}
void createFileName(char *str) {
// limited to 8.3 file format https://en.wikipedia.org/wiki/8.3_filename
// so .csv was removed
sprintf(str, "%d-%d-%d", gps.date.day(), gps.time.hour(), gps.time.minute());
}
/**
* delay while keep reading gps data
*/
void smartDelay(const unsigned long &delay) {
unsigned long initialTime = millis();
unsigned long currentTime;
do {
#ifdef DEBUG
if (gpsSerial.available() > 0) {
gps.encode(gpsSerial.read());
#else
if (Serial.available() > 0) {
gps.encode(Serial.read());
#endif
}
currentTime = millis();
} while (currentTime - initialTime < delay);
}
void setup() {
Serial.begin(9600);
#ifdef DEBUG
Serial.println(F("setup: initializing sensor platform..."));
gpsSerial.begin(9600);
#endif
// setup control led
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
// enable watchdog with 2 seconds timer
wdt_enable(WDTO_2S);
if(!sd.begin()) {
utils.error("setup: sd could not begin!");
}
// start acquiring first value, result is interrupt driven
// the dht sensor is having issues since the soldering on the board,
// this is a tmeporary work around to get valid values
if (dht.acquireAndWait() != IDDHTLIB_OK) {
utils.error("setup: dht could not acquire proper data!");
} else {
dht.saveLastValidData();
}
#ifdef DEBUG
Serial.println(F("setup: initialization went okay!"));
#endif
}
void loop() {
smartDelay(255);
if (firstEntry && gps.date.isValid() && gps.location.isValid()) {
// if valid state is entered, led is on
digitalWrite(LED_PIN, HIGH);
createFileName(fileName);
if (sd.exists(fileName)) {
#ifdef DEBUG
Serial.print(F("appending to file "));
Serial.println(fileName);
#endif
firstEntry = false;
} else {
#ifdef DEBUG
Serial.print(F("new log file "));
Serial.println(fileName);
#endif
firstEntry = false;
}
}
if (!firstEntry && gps.location.isValid()) {
// if valid state is entered, led is on
digitalWrite(LED_PIN, HIGH);
if (gps.location.isUpdated()) {
// get new dht value
dht.acquire();
char entry [40];
serialize(entry);
#ifdef DEBUG
Serial.println(entry);
#endif
if (!sd.writeToFile(fileName, entry)) {
utils.error("could not write data to file");
}
}
} else {
// blink for invalid gps data
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(LED_PIN, ledState);
}
// reset watchdog timer
wdt_reset();
}
<|endoftext|> |
<commit_before>#include "libhaloc/lc.h"
#include "libhaloc/utils.h"
#include <iostream>
#include <numeric>
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <string>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
namespace fs=boost::filesystem;
/** \brief Parameter constructor. Sets the parameter struct to default values.
*/
haloc::LoopClosure::Params::Params() :
work_dir(""),
desc_type("SIFT"),
num_proj(DEFAULT_NUM_PROJ),
desc_thresh(DEFAULT_DESC_THRESH),
epipolar_thresh(DEFAULT_EPIPOLAR_THRESH),
min_neighbour(DEFAULT_MIN_NEIGHBOUR),
n_candidates(DEFAULT_N_CANDIDATES),
min_matches(DEFAULT_MIN_MATCHES),
min_inliers(DEFAULT_MIN_INLIERS),
max_reproj_err(DEFAULT_MAX_REPROJ_ERR),
validate(DEFAULT_VALIDATE)
{}
/** \brief LoopClosure class constructor.
*/
haloc::LoopClosure::LoopClosure(){}
/** \brief Sets the class parameters.
* \param stuct of parameters.
*/
void haloc::LoopClosure::setParams(const Params& params)
{
params_ = params;
}
/** \brief Sets the camera model.
* \param Stereo camera model.
*/
void haloc::LoopClosure::setCameraModel(image_geometry::StereoCameraModel stereo_camera_model, Mat camera_matrix)
{
img_.setCameraModel(stereo_camera_model);
camera_matrix_ = camera_matrix;
}
/** \brief Initializes the loop closure class.
*/
void haloc::LoopClosure::init()
{
// Working directory sanity check
if (params_.work_dir[params_.work_dir.length()-1] != '/')
params_.work_dir += "/ex_" + boost::lexical_cast<string>(time(0));
else
params_.work_dir += "ex_" + boost::lexical_cast<string>(time(0));
// Create the directory to store the keypoints and descriptors
if (fs::is_directory(params_.work_dir))
fs::remove_all(params_.work_dir);
fs::path dir(params_.work_dir);
if (!fs::create_directory(dir))
ROS_ERROR("[Haloc:] ERROR -> Impossible to create the execution directory.");
// Initialize image properties
haloc::Image::Params img_params;
img_params.desc_type = params_.desc_type;
img_params.desc_thresh = params_.desc_thresh;
img_params.epipolar_thresh = params_.epipolar_thresh;
img_.setParams(img_params);
// Initialize hash
haloc::Hash::Params hash_params;
hash_params.num_proj = params_.num_proj;
hash_.setParams(hash_params);
// Init main variables
hash_table_.clear();
img_idx_ = 0;
}
/** \brief Finalizes the loop closure class.
*/
void haloc::LoopClosure::finalize()
{
// Remove the temporal directory
if (fs::is_directory(params_.work_dir))
fs::remove_all(params_.work_dir);
}
/** \brief Compute kp, desc and hash for one image (mono verion).
* \param cvMat containing the image.
* \param human readable name for this image
*/
void haloc::LoopClosure::setNode(Mat img, string name)
{
// Set the image
img_.setMono(img);
// Save kp and descriptors
vector<Point3f> empty;
FileStorage fs(params_.work_dir+"/"+boost::lexical_cast<string>(img_idx_)+".yml", FileStorage::WRITE);
write(fs, "name", name);
write(fs, "kp", img_.getKp());
write(fs, "desc", img_.getDesc());
write(fs, "threed", empty);
fs.release();
img_idx_++;
}
/** \brief Compute kp, desc and hash for two images (stereo verion).
* \param cvMat containing the left image.
* \param cvMat containing the right image.
* \param human readable name for this image
*/
void haloc::LoopClosure::setNode(Mat img_l, Mat img_r, string name)
{
// Set the image
img_.setStereo(img_l, img_r);
// Save kp and descriptors
FileStorage fs(params_.work_dir+"/"+boost::lexical_cast<string>(img_idx_)+".yml", FileStorage::WRITE);
write(fs, "name", name);
write(fs, "kp", img_.getKp());
write(fs, "desc", img_.getDesc());
write(fs, "threed", img_.get3D());
fs.release();
img_idx_++;
}
/** \brief Try to find a loop closure between last node and all other nodes.
* @return true if valid loop closure, false otherwise.
* \param Return the index of the image that closes loop (-1 if no loop).
*/
bool haloc::LoopClosure::getLoopClosure(int& lc_img_idx, string& lc_name)
{
tf::Transform trans;
return getLoopClosure(lc_img_idx, lc_name, trans);
}
/** \brief Try to find a loop closure between last node and all other nodes.
* @return true if valid loop closure, false otherwise.
* \param Return the index of the image that closes loop (-1 if no loop).
* \param Return the name of the image that closes loop (empty if no loop).
* \param Return the transform between nodes if loop closure is valid.
*/
bool haloc::LoopClosure::getLoopClosure(int& lc_img_idx, string& lc_name, tf::Transform& trans)
{
// Initialize hash
if (!hash_.isInitialized())
{
hash_.init(img_.getDesc(), true);
return false;
}
// Compute the hash for this image
vector<float> hash_val = hash_.getHash(img_.getDesc());
hash_table_.push_back(make_pair(img_idx_-1, hash_val));
// Check if enough neighours
if (hash_table_.size() <= params_.min_neighbour)
return false;
// Compute the hash matchings for this image with all other sequence
vector< pair<int,float> > matchings;
for (uint i=0; i<hash_table_.size()-params_.min_neighbour; i++)
{
// Hash matching
vector<float> cur_hash = hash_table_[i].second;
float m = hash_.match(hash_val, cur_hash);
matchings.push_back(make_pair(hash_table_[i].first, m));
}
// Sort the hash matchings
sort(matchings.begin(), matchings.end(), haloc::Utils::sortByMatching);
// Check for loop closure
trans.setIdentity();
lc_img_idx = -1;
lc_name = "";
int best_m = 0;
int matches = 0;
int inliers = 0;
bool valid = false;
while (best_m<params_.n_candidates)
{
// Sanity check
if(best_m >= matchings.size())
{
best_m = 0;
break;
}
// Loop-closure?
valid = compute(img_,
params_.work_dir+"/"+boost::lexical_cast<string>(matchings[best_m].first)+".yml",
lc_name,
matches,
inliers,
trans);
// If the loop closure is valid and the seconds step validation is disabled, that's all.
if (valid && !params_.validate) break;
// Validate the loop closure?
if (valid && params_.validate)
{
// Initialize validation
bool validate_valid = false;
int matches_val, inliers_val;
tf::Transform trans_val;
string tmp_name;
// Loop closure for the previous image?
validate_valid = compute(img_,
params_.work_dir+"/"+boost::lexical_cast<string>(matchings[best_m].first - 1)+".yml",
tmp_name,
matches_val,
inliers_val,
trans_val);
if (!validate_valid)
{
// Previous validation does not works, try to validate with the next image
validate_valid = compute(img_,
params_.work_dir+"/"+boost::lexical_cast<string>(matchings[best_m].first + 1)+".yml",
tmp_name,
matches_val,
inliers_val,
trans_val);
}
// If validation, exit. If not, mark as non-valid
if (validate_valid)
break;
else
valid = false;
}
best_m++;
}
// Get the image of the loop closure
if (valid && best_m < matchings.size())
lc_img_idx = matchings[best_m].first;
else
lc_name = "";
// Return true if any valid loop closure has been found.
return valid;
}
/** \brief Compute the loop closure (if any).
* @return true if valid loop closure, false otherwise.
* \param Reference image object.
* \param Current image filename with all the properties.
* \param Return the number of matches found.
* \param Return the number of inliers found.
* \param Return the transform between nodes if loop closure is valid.
*/
bool haloc::LoopClosure::compute(Image ref_image,
string cur_filename,
string &lc_name,
int &matches,
int &inliers,
tf::Transform& trans)
{
// Initialize outputs
matches = 0;
inliers = 0;
// Sanity check
if ( !fs::exists(cur_filename) ) return false;
// Get the image keypoints and descriptors
FileStorage fs;
fs.open(cur_filename, FileStorage::READ);
if (!fs.isOpened())
ROS_ERROR("[Haloc:] ERROR -> Failed to open the image keypoints and descriptors.");
vector<Point2f> cur_kp;
Mat cur_desc;
vector<Point3f> points_3d;
fs["name"] >> lc_name;
fs["kp"] >> cur_kp;
fs["desc"] >> cur_desc;
fs["threed"] >> points_3d;
fs.release();
// Descriptors crosscheck matching
vector<DMatch> desc_matches;
Mat match_mask;
haloc::Utils::crossCheckThresholdMatching(ref_image.getDesc(),
cur_desc,
params_.desc_thresh,
match_mask, desc_matches);
matches = (int)desc_matches.size();
// Check matches size
if (matches < params_.min_matches)
return false;
// Get the matched keypoints
vector<Point2f> ref_kp = ref_image.getKp();
vector<Point2f> ref_points;
vector<Point2f> cur_points;
for(int i=0; i<matches; i++)
{
ref_points.push_back(ref_kp[desc_matches[i].queryIdx]);
cur_points.push_back(cur_kp[desc_matches[i].trainIdx]);
}
// Proceed depending on mono or stereo
if (points_3d.size() == 0) // Mono
{
// Check the epipolar geometry
Mat status;
Mat F = findFundamentalMat(ref_points, cur_points, FM_RANSAC, params_.epipolar_thresh, 0.999, status);
// Is the fundamental matrix valid?
Scalar f_sum_parts = cv::sum(F);
float f_sum = (float)f_sum_parts[0] + (float)f_sum_parts[1] + (float)f_sum_parts[2];
if (f_sum < 1e-3)
return false;
// Check inliers size
inliers = (int)cv::sum(status)[0];
if (inliers < params_.min_inliers)
return false;
}
else // Stereo
{
Mat rvec, tvec;
vector<int> solvepnp_inliers;
solvePnPRansac(points_3d, cur_points, camera_matrix_,
cv::Mat(), rvec, tvec, false,
100, params_.max_reproj_err,
40, solvepnp_inliers);
inliers = (int)solvepnp_inliers.size();
if (inliers < params_.min_inliers)
return false;
trans = haloc::Utils::buildTransformation(rvec, tvec);
}
// If we arrive here, there is a loop closure.
return true;
}<commit_msg>Fix incorrect indices for stereo loop closure<commit_after>#include "libhaloc/lc.h"
#include "libhaloc/utils.h"
#include <iostream>
#include <numeric>
#include <stdlib.h>
#include <fstream>
#include <sstream>
#include <string>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
namespace fs=boost::filesystem;
/** \brief Parameter constructor. Sets the parameter struct to default values.
*/
haloc::LoopClosure::Params::Params() :
work_dir(""),
desc_type("SIFT"),
num_proj(DEFAULT_NUM_PROJ),
desc_thresh(DEFAULT_DESC_THRESH),
epipolar_thresh(DEFAULT_EPIPOLAR_THRESH),
min_neighbour(DEFAULT_MIN_NEIGHBOUR),
n_candidates(DEFAULT_N_CANDIDATES),
min_matches(DEFAULT_MIN_MATCHES),
min_inliers(DEFAULT_MIN_INLIERS),
max_reproj_err(DEFAULT_MAX_REPROJ_ERR),
validate(DEFAULT_VALIDATE)
{}
/** \brief LoopClosure class constructor.
*/
haloc::LoopClosure::LoopClosure(){}
/** \brief Sets the class parameters.
* \param stuct of parameters.
*/
void haloc::LoopClosure::setParams(const Params& params)
{
params_ = params;
}
/** \brief Sets the camera model.
* \param Stereo camera model.
*/
void haloc::LoopClosure::setCameraModel(image_geometry::StereoCameraModel stereo_camera_model, Mat camera_matrix)
{
img_.setCameraModel(stereo_camera_model);
camera_matrix_ = camera_matrix;
}
/** \brief Initializes the loop closure class.
*/
void haloc::LoopClosure::init()
{
// Working directory sanity check
if (params_.work_dir[params_.work_dir.length()-1] != '/')
params_.work_dir += "/ex_" + boost::lexical_cast<string>(time(0));
else
params_.work_dir += "ex_" + boost::lexical_cast<string>(time(0));
// Create the directory to store the keypoints and descriptors
if (fs::is_directory(params_.work_dir))
fs::remove_all(params_.work_dir);
fs::path dir(params_.work_dir);
if (!fs::create_directory(dir))
ROS_ERROR("[Haloc:] ERROR -> Impossible to create the execution directory.");
// Initialize image properties
haloc::Image::Params img_params;
img_params.desc_type = params_.desc_type;
img_params.desc_thresh = params_.desc_thresh;
img_params.epipolar_thresh = params_.epipolar_thresh;
img_.setParams(img_params);
// Initialize hash
haloc::Hash::Params hash_params;
hash_params.num_proj = params_.num_proj;
hash_.setParams(hash_params);
// Init main variables
hash_table_.clear();
img_idx_ = 0;
}
/** \brief Finalizes the loop closure class.
*/
void haloc::LoopClosure::finalize()
{
// Remove the temporal directory
if (fs::is_directory(params_.work_dir))
fs::remove_all(params_.work_dir);
}
/** \brief Compute kp, desc and hash for one image (mono verion).
* \param cvMat containing the image.
* \param human readable name for this image
*/
void haloc::LoopClosure::setNode(Mat img, string name)
{
// Set the image
img_.setMono(img);
// Save kp and descriptors
vector<Point3f> empty;
FileStorage fs(params_.work_dir+"/"+boost::lexical_cast<string>(img_idx_)+".yml", FileStorage::WRITE);
write(fs, "name", name);
write(fs, "kp", img_.getKp());
write(fs, "desc", img_.getDesc());
write(fs, "threed", empty);
fs.release();
img_idx_++;
}
/** \brief Compute kp, desc and hash for two images (stereo verion).
* \param cvMat containing the left image.
* \param cvMat containing the right image.
* \param human readable name for this image
*/
void haloc::LoopClosure::setNode(Mat img_l, Mat img_r, string name)
{
// Set the image
img_.setStereo(img_l, img_r);
// Save kp and descriptors
FileStorage fs(params_.work_dir+"/"+boost::lexical_cast<string>(img_idx_)+".yml", FileStorage::WRITE);
write(fs, "name", name);
write(fs, "kp", img_.getKp());
write(fs, "desc", img_.getDesc());
write(fs, "threed", img_.get3D());
fs.release();
img_idx_++;
}
/** \brief Try to find a loop closure between last node and all other nodes.
* @return true if valid loop closure, false otherwise.
* \param Return the index of the image that closes loop (-1 if no loop).
*/
bool haloc::LoopClosure::getLoopClosure(int& lc_img_idx, string& lc_name)
{
tf::Transform trans;
return getLoopClosure(lc_img_idx, lc_name, trans);
}
/** \brief Try to find a loop closure between last node and all other nodes.
* @return true if valid loop closure, false otherwise.
* \param Return the index of the image that closes loop (-1 if no loop).
* \param Return the name of the image that closes loop (empty if no loop).
* \param Return the transform between nodes if loop closure is valid.
*/
bool haloc::LoopClosure::getLoopClosure(int& lc_img_idx, string& lc_name, tf::Transform& trans)
{
// Initialize hash
if (!hash_.isInitialized())
{
hash_.init(img_.getDesc(), true);
return false;
}
// Compute the hash for this image
vector<float> hash_val = hash_.getHash(img_.getDesc());
hash_table_.push_back(make_pair(img_idx_-1, hash_val));
// Check if enough neighours
if (hash_table_.size() <= params_.min_neighbour)
return false;
// Compute the hash matchings for this image with all other sequence
vector< pair<int,float> > matchings;
for (uint i=0; i<hash_table_.size()-params_.min_neighbour; i++)
{
// Hash matching
vector<float> cur_hash = hash_table_[i].second;
float m = hash_.match(hash_val, cur_hash);
matchings.push_back(make_pair(hash_table_[i].first, m));
}
// Sort the hash matchings
sort(matchings.begin(), matchings.end(), haloc::Utils::sortByMatching);
// Check for loop closure
trans.setIdentity();
lc_img_idx = -1;
lc_name = "";
int best_m = 0;
int matches = 0;
int inliers = 0;
bool valid = false;
while (best_m<params_.n_candidates)
{
// Sanity check
if(best_m >= matchings.size())
{
best_m = 0;
break;
}
// Loop-closure?
valid = compute(img_,
params_.work_dir+"/"+boost::lexical_cast<string>(matchings[best_m].first)+".yml",
lc_name,
matches,
inliers,
trans);
// If the loop closure is valid and the seconds step validation is disabled, that's all.
if (valid && !params_.validate) break;
// Validate the loop closure?
if (valid && params_.validate)
{
// Initialize validation
bool validate_valid = false;
int matches_val, inliers_val;
tf::Transform trans_val;
string tmp_name;
// Loop closure for the previous image?
validate_valid = compute(img_,
params_.work_dir+"/"+boost::lexical_cast<string>(matchings[best_m].first - 1)+".yml",
tmp_name,
matches_val,
inliers_val,
trans_val);
if (!validate_valid)
{
// Previous validation does not works, try to validate with the next image
validate_valid = compute(img_,
params_.work_dir+"/"+boost::lexical_cast<string>(matchings[best_m].first + 1)+".yml",
tmp_name,
matches_val,
inliers_val,
trans_val);
}
// If validation, exit. If not, mark as non-valid
if (validate_valid)
break;
else
valid = false;
}
best_m++;
}
// Get the image of the loop closure
if (valid && best_m < matchings.size())
lc_img_idx = matchings[best_m].first;
else
lc_name = "";
// Return true if any valid loop closure has been found.
return valid;
}
/** \brief Compute the loop closure (if any).
* @return true if valid loop closure, false otherwise.
* \param Reference image object.
* \param Current image filename with all the properties.
* \param Return the number of matches found.
* \param Return the number of inliers found.
* \param Return the transform between nodes if loop closure is valid.
*/
bool haloc::LoopClosure::compute(Image ref_image,
string cur_filename,
string &lc_name,
int &matches,
int &inliers,
tf::Transform& trans)
{
// Initialize outputs
matches = 0;
inliers = 0;
// Sanity check
if ( !fs::exists(cur_filename) ) return false;
// Get the image keypoints and descriptors
FileStorage fs;
fs.open(cur_filename, FileStorage::READ);
if (!fs.isOpened())
ROS_ERROR("[Haloc:] ERROR -> Failed to open the image keypoints and descriptors.");
vector<Point2f> cur_kp;
Mat cur_desc;
vector<Point3f> cur_3d;
fs["name"] >> lc_name;
fs["kp"] >> cur_kp;
fs["desc"] >> cur_desc;
fs["threed"] >> cur_3d;
fs.release();
// Descriptors crosscheck matching
vector<DMatch> desc_matches;
Mat match_mask;
haloc::Utils::crossCheckThresholdMatching(cur_desc,
ref_image.getDesc(),
params_.desc_thresh,
match_mask, desc_matches);
matches = (int)desc_matches.size();
// Check matches size
if (matches < params_.min_matches)
return false;
// Get the matched keypoints
vector<Point2f> ref_kp = ref_image.getKp();
vector<Point2f> ref_matched_kp;
vector<Point2f> cur_matched_kp;
vector<Point3f> cur_matched_3d_points;
for(int i=0; i<matches; i++)
{
ref_matched_kp.push_back(ref_kp[desc_matches[i].trainIdx]);
cur_matched_kp.push_back(cur_kp[desc_matches[i].queryIdx]);
// Only stereo
if (cur_3d.size() == 0)
{
cur_matched_3d_points.push_back(cur_3d[desc_matches[i].queryIdx]);
}
}
// Proceed depending on mono or stereo
if (cur_3d.size() == 0) // Mono
{
// Check the epipolar geometry
Mat status;
Mat F = findFundamentalMat(cur_matched_kp, ref_matched_kp, FM_RANSAC, params_.epipolar_thresh, 0.999, status);
// Is the fundamental matrix valid?
Scalar f_sum_parts = cv::sum(F);
float f_sum = (float)f_sum_parts[0] + (float)f_sum_parts[1] + (float)f_sum_parts[2];
if (f_sum < 1e-3)
return false;
// Check inliers size
inliers = (int)cv::sum(status)[0];
if (inliers < params_.min_inliers)
return false;
}
else // Stereo
{
Mat rvec, tvec;
vector<int> solvepnp_inliers;
solvePnPRansac(cur_matched_3d_points, ref_matched_kp, camera_matrix_,
cv::Mat(), rvec, tvec, false,
100, params_.max_reproj_err,
40, solvepnp_inliers);
inliers = (int)solvepnp_inliers.size();
if (inliers < params_.min_inliers)
return false;
trans = haloc::Utils::buildTransformation(rvec, tvec);
}
// If we arrive here, there is a loop closure.
return true;
}<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <list>
#include <iomanip>
#include <string>
#if WIN32
#include <windows.h>
#else
#include <sys/ioctl.h>
#include <stdio.h>
#include <unistd.h>
#endif
int main(int argc, char** argv)
{
std::list<std::wstring> consoleLines;
int columns, rows;
bool isRunning = true;
consoleLines.push_front(std::wstring(L"[00:00] System: dc-console v1.0"));
while (isRunning)
{
#if WIN32
std::system("cls");
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
#else
std::system("clear");
struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
columns = w.ws_col;
rows = w.ws_row;
#endif
for (int i = 0; i < rows - 1; ++i)
{
if (consoleLines.size() > rows - i - 2)
{
std::list<std::wstring>::iterator it = std::next(consoleLines.begin(), rows - i - 2);
std::cout << std::setiosflags(std::ios::left) << std::setw(columns) << std::string(it->begin(), it->end());
}
else
std::cout << std::setiosflags(std::ios::left) << std::setw(columns) << " ";
}
std::cout << "> ";
std::string line;
std::getline(std::cin, line);
if (line == "exit")
isRunning = false;
else
consoleLines.push_front(std::wstring(L"[00:00] User: ").append(std::wstring(line.begin(), line.end())));
}
return 0;
}<commit_msg>Fixed build error on linux.<commit_after>#include <iostream>
#include <cstdlib>
#include <list>
#include <iomanip>
#include <string>
#if WIN32
#include <windows.h>
#else
#include <sys/ioctl.h>
#include <stdio.h>
#include <unistd.h>
#endif
int main(int argc, char** argv)
{
std::list<std::wstring> consoleLines;
int columns, rows;
bool isRunning = true;
consoleLines.push_front(std::wstring(L"[00:00] System: dc-console v1.0"));
while (isRunning)
{
#if WIN32
std::system("cls");
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
#else
std::system("clear");
struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
columns = w.ws_col;
rows = w.ws_row;
#endif
for (int i = 0; i < rows - 1; ++i)
{
if (consoleLines.size() > rows - i - 2)
{
std::list<std::wstring>::iterator it = consoleLines.begin();
std::advance(it, rows - i - 2);
std::cout << std::setiosflags(std::ios::left) << std::setw(columns) << std::string(it->begin(), it->end());
}
else
std::cout << std::setiosflags(std::ios::left) << std::setw(columns) << " ";
}
std::cout << "> ";
std::string line;
std::getline(std::cin, line);
if (line == "exit")
isRunning = false;
else
consoleLines.push_front(std::wstring(L"[00:00] User: ").append(std::wstring(line.begin(), line.end())));
}
return 0;
}<|endoftext|> |
<commit_before>//For colored output
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_RESET "\x1b[0m"
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include "Program.h"
using namespace std;
const GLuint SCREEN_WIDTH = 500;
const GLuint SCREEN_HEIGHT = 500;
GLfloat timer;
bool show3d;
Program *program;
GLFWwindow* gWindow = NULL;
static void Render() {
//White Background
glClearColor(1, 1, 1, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Update Timer
timer+=0.01;
GLuint timerLoc = glGetUniformLocation(program->getID(), "timer");
glUniform1f(timerLoc, timer);
if(show3d){
//Draw Cube
glDrawArrays(GL_TRIANGLES,0, 36);
}else{
//Draw Triangle
glDrawArrays(GL_TRIANGLES, 0, 3);
}
glfwSwapBuffers(gWindow);
}
//Compile Link and Create Shader Program
void createShaders(){
Shader vertex("./shaders/vert.glsl",GL_VERTEX_SHADER);
Shader fragment("./shaders/frag.glsl",GL_FRAGMENT_SHADER);
program = new Program();
program->attachShader(vertex);
program->attachShader(fragment);
program->link();
program->use();
if(Logger::show){
program->printActiveAttribs();
program->printActiveUniforms();
}
}
//Generate VBO and VAO
void createAttributes(float positionData[],int sizePos, float colorData[], int sizeColor){
//Generate vertex buffer objects
GLuint vboHandles[2];
glGenBuffers(2,vboHandles);
//Hold onto an vbo id
GLuint positionBufferHandle = vboHandles[0];
GLuint colorBufferHandle = vboHandles[1];
//Position Binding - bind data to vbo
glBindBuffer(GL_ARRAY_BUFFER,positionBufferHandle);
glBufferData(GL_ARRAY_BUFFER, sizePos, positionData, GL_STATIC_DRAW);
//Color binding - bind data to vbo
glBindBuffer(GL_ARRAY_BUFFER,colorBufferHandle);
glBufferData(GL_ARRAY_BUFFER, sizeColor, colorData, GL_STATIC_DRAW);
//generate a single vao
GLuint vao;
glGenVertexArrays(1,&vao);
glBindVertexArray(vao);
//Link attribute name with location or you can do it in the shader
GLuint positionLocation = 0;
GLuint colorLocation = 1;
glBindAttribLocation(program->getID(), positionLocation,"VertexPosition");
glBindAttribLocation(program->getID(), colorLocation,"VertexColor");
//Make location an array type
glEnableVertexAttribArray(positionLocation);
glEnableVertexAttribArray(colorLocation);
//bind vao to vbo
glBindBuffer(GL_ARRAY_BUFFER, positionBufferHandle);
//specify datatype and info of vao
glVertexAttribPointer(positionLocation, 3, GL_FLOAT, GL_FALSE, 0, NULL);
//do the same for color buffer
glBindBuffer(GL_ARRAY_BUFFER, colorBufferHandle);
glVertexAttribPointer(colorLocation, 3, GL_FLOAT, GL_FALSE, 0, NULL);
}
void triangleSetup(){
//Triangle Vertices Coordinates (Model Coordinates)
float positionData[] ={
-0.8f,-0.8f,0.0f,
0.8f,-0.8f,0.0f,
0.0f,0.8f,0.0f
};
//Triangle Vertice Colors
float colorData[]={
1.0f,0.0f,0.0f,
0.0f,0.0f,1.0f,
0.0f,1.0f,0.0f
};
createAttributes(positionData, sizeof(positionData), colorData, sizeof(colorData));
}
void cubeSetup(){
//Cube Vertices Coordinates (Model Coordinates)
float positionData[] ={
-1.0f,-1.0f,-1.0f,
-1.0f,-1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f,-1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f,-1.0f,
-1.0f, 1.0f,-1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f,-1.0f, 1.0f
};
//Cube vertice colors, one face has 2 triangles with different colors to show that it is made up with triangles
float colorData[]={
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
1.000f, 0.000f, 0.000f,
1.000f, 0.000f, 0.000f,
1.000f, 0.000f, 0.000f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
0.800f, 0.000f, 0.000f,
0.800f, 0.000f, 0.000f,
0.800f, 0.000f, 0.000f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
1.000f, 0.000f, 0.000f,
1.000f, 0.000f, 0.000f,
1.000f, 0.000f, 0.000f,
0.000f, 1.000f, 0.000f,
0.000f, 1.000f, 0.000f,
0.000f, 1.000f, 0.000f,
0.000f, 1.000f, 0.000f,
0.000f, 1.000f, 0.000f,
0.000f, 1.000f, 0.000f,
0.000f, 0.000f, 1.000f,
0.000f, 0.000f, 1.000f,
0.000f, 0.000f, 1.000f,
0.000f, 0.000f, 1.000f,
0.000f, 0.000f, 1.000f,
0.000f, 0.000f, 1.000f,
1.000f, 0.000f, 0.000f,
1.000f, 0.000f, 0.000f,
1.000f, 0.000f, 0.000f,
};
createAttributes(positionData, sizeof(positionData), colorData, sizeof(colorData));
}
void printInfo(){
char buff[255];
//Print OpenGl Info
Logger::log(ANSI_COLOR_CYAN "*****************************************************************************" ANSI_COLOR_RESET);
snprintf(buff, sizeof(buff), "OpenGL version: %s", glGetString(GL_VERSION));
Logger::log(buff);
snprintf(buff, sizeof(buff), "GLSL version: %s", glGetString(GL_SHADING_LANGUAGE_VERSION));
Logger::log(buff);
snprintf(buff, sizeof(buff), "Vendor: %s", glGetString(GL_VENDOR));
Logger::log(buff);
snprintf(buff, sizeof(buff), "Renderer: %s", glGetString(GL_RENDERER));
Logger::log(buff);
//Print Window Position Info
Logger::log(ANSI_COLOR_CYAN"--------------------------------------------------------------------------------" ANSI_COLOR_RESET);
int xpos, ypos;
glfwGetWindowPos(gWindow, &xpos, &ypos);
snprintf(buff, sizeof(buff), "Window Position\n x: %d, y: %d",xpos,ypos);
Logger::log(buff);
Logger::log("Set Window Postion in the makefile otherwise it defaults to center of screen.");
Logger::log(ANSI_COLOR_CYAN "-----------------------------------------------------------------------------" ANSI_COLOR_RESET);
Logger::log(ANSI_COLOR_CYAN "********************************************************************************\n" ANSI_COLOR_RESET);
}
void OnError(int errorCode, const char* msg) {
throw std::runtime_error(msg);
}
void key_press(GLFWwindow* window, int key, int scancode, int action, int mods){
//Recompile Shaders on C key press
if (glfwGetKey(window, GLFW_KEY_C) == GLFW_PRESS){
Logger::log(ANSI_COLOR_MAGENTA "================================================================================");
Logger::log(" Recompiling Shaders ");
Logger::log("================================================================================");
createShaders();
Logger::log("================================================================================");
Logger::log(" Compilation Complete ");
Logger::log("================================================================================ " ANSI_COLOR_RESET);
}
//Use the Cube
if(glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS){
show3d=true;
Logger::log(ANSI_COLOR_MAGENTA "================================================================================");
Logger::log(" Using Cube ");
Logger::log("================================================================================" ANSI_COLOR_RESET);
cubeSetup();
}
//Use the Triangle
if(glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS){
show3d=false;
triangleSetup();
Logger::log(ANSI_COLOR_MAGENTA "================================================================================");
Logger::log(" Using Triangle ");
Logger::log("================================================================================" ANSI_COLOR_RESET);
}
}
int main(int argc, char **argv)
{
Logger::log(ANSI_COLOR_CYAN "################################################################################");
Logger::log(" Starting GLFW and OpenGL ");
Logger::log("################################################################################" ANSI_COLOR_RESET);
//Logger::show =false;
show3d=false;
glfwSetErrorCallback(OnError);
if(!glfwInit())
throw std::runtime_error("glfwInit failed");
// open a window with GLFW
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
gWindow = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "OpenGL Tutorial", NULL, NULL);
//Set Window Position or center of screen if not specified
if(argc >2 && atoi(argv[1]) != -1 && atoi(argv[2]) != -1){
glfwSetWindowPos(gWindow,atoi(argv[1]),atoi(argv[2]));
}
//Disallow Resizing
glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);
if(!gWindow)
throw std::runtime_error("glfwCreateWindow failed. Can your hardware handle OpenGL 4.1?");
// GLFW settings
glfwMakeContextCurrent(gWindow);
// initialise GLEW with core
glewExperimental = GL_TRUE;
if(glewInit() != GLEW_OK)
throw std::runtime_error("glewInit failed");
// print out some environment info
printInfo();
createShaders();
triangleSetup();
//Link after Compilation and VBO and VAO are created
program->link();
program->use();
if(Logger::show){
program->printActiveAttribs();
program->printActiveUniforms();
}
//Hide things that are behind others
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
//start timer
timer = 0.0;
//Create a screen size uniform
GLuint location = glGetUniformLocation(program->getID(),"screen");
glUniform2f(location,SCREEN_WIDTH, SCREEN_HEIGHT);
//Handle Key events
glfwSetKeyCallback(gWindow, key_press);
//Run Loop
while(!glfwWindowShouldClose(gWindow)){
glfwPollEvents();
Render();
}
glfwTerminate();
}
<commit_msg>fix location bug<commit_after>//For colored output
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_RESET "\x1b[0m"
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include "Program.h"
using namespace std;
const GLuint SCREEN_WIDTH = 500;
const GLuint SCREEN_HEIGHT = 500;
GLfloat timer;
bool show3d;
Program *program;
GLFWwindow* gWindow = NULL;
static void Render() {
//White Background
glClearColor(1, 1, 1, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Update Timer
timer+=0.01;
GLuint timerLoc = glGetUniformLocation(program->getID(), "timer");
glUniform1f(timerLoc, timer);
if(show3d){
//Draw Cube
glDrawArrays(GL_TRIANGLES,0, 36);
}else{
//Draw Triangle
glDrawArrays(GL_TRIANGLES, 0, 3);
}
glfwSwapBuffers(gWindow);
}
//Compile Link and Create Shader Program
void createShaders(){
Shader vertex("./shaders/vert.glsl",GL_VERTEX_SHADER);
Shader fragment("./shaders/frag.glsl",GL_FRAGMENT_SHADER);
program = new Program();
program->attachShader(vertex);
program->attachShader(fragment);
//Link attribute name with location or you can do it in the shader
// This code must happen each time program links!!!
// positionLocation = 0;
// colorLocation = 1;
glBindAttribLocation(program->getID(), 0,"VertexPosition");
glBindAttribLocation(program->getID(), 1,"VertexColor");
program->link();
program->use();
if(Logger::show){
program->printActiveAttribs();
program->printActiveUniforms();
}
}
//Generate VBO and VAO
void createAttributes(float positionData[],int sizePos, float colorData[], int sizeColor){
//Generate vertex buffer objects
GLuint vboHandles[2];
glGenBuffers(2,vboHandles);
//Hold onto an vbo id
GLuint positionBufferHandle = vboHandles[0];
GLuint colorBufferHandle = vboHandles[1];
//Position Binding - bind data to vbo
glBindBuffer(GL_ARRAY_BUFFER,positionBufferHandle);
glBufferData(GL_ARRAY_BUFFER, sizePos, positionData, GL_STATIC_DRAW);
//Color binding - bind data to vbo
glBindBuffer(GL_ARRAY_BUFFER,colorBufferHandle);
glBufferData(GL_ARRAY_BUFFER, sizeColor, colorData, GL_STATIC_DRAW);
//generate a single vao
GLuint vao;
glGenVertexArrays(1,&vao);
glBindVertexArray(vao);
//Attribute Location Identifiers
GLuint positionLocation = 0;
GLuint colorLocation = 1;
//Make location an array type
glEnableVertexAttribArray(positionLocation);
glEnableVertexAttribArray(colorLocation);
//bind vao to vbo
glBindBuffer(GL_ARRAY_BUFFER, positionBufferHandle);
//specify datatype and info of vao
glVertexAttribPointer(positionLocation, 3, GL_FLOAT, GL_FALSE, 0, NULL);
//do the same for color buffer
glBindBuffer(GL_ARRAY_BUFFER, colorBufferHandle);
glVertexAttribPointer(colorLocation, 3, GL_FLOAT, GL_FALSE, 0, NULL);
}
void triangleSetup(){
//Triangle Vertices Coordinates (Model Coordinates)
float positionData[] ={
-0.8f,-0.8f,0.0f,
0.8f,-0.8f,0.0f,
0.0f,0.8f,0.0f
};
//Triangle Vertice Colors
float colorData[]={
1.0f,0.0f,0.0f,
0.0f,0.0f,1.0f,
0.0f,1.0f,0.0f
};
createAttributes(positionData, sizeof(positionData), colorData, sizeof(colorData));
}
void cubeSetup(){
//Cube Vertices Coordinates (Model Coordinates)
float positionData[] ={
-1.0f,-1.0f,-1.0f,
-1.0f,-1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f,-1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f,-1.0f,
-1.0f, 1.0f,-1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f,-1.0f, 1.0f
};
//Cube vertice colors, one face has 2 triangles with different colors to show that it is made up with triangles
float colorData[]={
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
1.000f, 0.000f, 0.000f,
1.000f, 0.000f, 0.000f,
1.000f, 0.000f, 0.000f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
0.800f, 0.000f, 0.000f,
0.800f, 0.000f, 0.000f,
0.800f, 0.000f, 0.000f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
0.583f, 0.771f, 0.014f,
1.000f, 0.000f, 0.000f,
1.000f, 0.000f, 0.000f,
1.000f, 0.000f, 0.000f,
0.000f, 1.000f, 0.000f,
0.000f, 1.000f, 0.000f,
0.000f, 1.000f, 0.000f,
0.000f, 1.000f, 0.000f,
0.000f, 1.000f, 0.000f,
0.000f, 1.000f, 0.000f,
0.000f, 0.000f, 1.000f,
0.000f, 0.000f, 1.000f,
0.000f, 0.000f, 1.000f,
0.000f, 0.000f, 1.000f,
0.000f, 0.000f, 1.000f,
0.000f, 0.000f, 1.000f,
1.000f, 0.000f, 0.000f,
1.000f, 0.000f, 0.000f,
1.000f, 0.000f, 0.000f,
};
createAttributes(positionData, sizeof(positionData), colorData, sizeof(colorData));
}
void printInfo(){
char buff[255];
//Print OpenGl Info
Logger::log(ANSI_COLOR_CYAN "*****************************************************************************" ANSI_COLOR_RESET);
snprintf(buff, sizeof(buff), "OpenGL version: %s", glGetString(GL_VERSION));
Logger::log(buff);
snprintf(buff, sizeof(buff), "GLSL version: %s", glGetString(GL_SHADING_LANGUAGE_VERSION));
Logger::log(buff);
snprintf(buff, sizeof(buff), "Vendor: %s", glGetString(GL_VENDOR));
Logger::log(buff);
snprintf(buff, sizeof(buff), "Renderer: %s", glGetString(GL_RENDERER));
Logger::log(buff);
//Print Window Position Info
Logger::log(ANSI_COLOR_CYAN"--------------------------------------------------------------------------------" ANSI_COLOR_RESET);
int xpos, ypos;
glfwGetWindowPos(gWindow, &xpos, &ypos);
snprintf(buff, sizeof(buff), "Window Position\n x: %d, y: %d",xpos,ypos);
Logger::log(buff);
Logger::log("Set Window Postion in the makefile otherwise it defaults to center of screen.");
Logger::log(ANSI_COLOR_CYAN "-----------------------------------------------------------------------------" ANSI_COLOR_RESET);
Logger::log(ANSI_COLOR_CYAN "********************************************************************************\n" ANSI_COLOR_RESET);
}
void OnError(int errorCode, const char* msg) {
throw std::runtime_error(msg);
}
void key_press(GLFWwindow* window, int key, int scancode, int action, int mods){
//Recompile Shaders on C key press
if (glfwGetKey(window, GLFW_KEY_C) == GLFW_PRESS){
Logger::log(ANSI_COLOR_MAGENTA "================================================================================");
Logger::log(" Recompiling Shaders ");
Logger::log("================================================================================");
createShaders();
Logger::log("================================================================================");
Logger::log(" Compilation Complete ");
Logger::log("================================================================================ " ANSI_COLOR_RESET);
}
//Use the Cube
if(glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS){
show3d=true;
Logger::log(ANSI_COLOR_MAGENTA "================================================================================");
Logger::log(" Using Cube ");
Logger::log("================================================================================" ANSI_COLOR_RESET);
cubeSetup();
}
//Use the Triangle
if(glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS){
show3d=false;
triangleSetup();
Logger::log(ANSI_COLOR_MAGENTA "================================================================================");
Logger::log(" Using Triangle ");
Logger::log("================================================================================" ANSI_COLOR_RESET);
}
}
int main(int argc, char **argv)
{
Logger::log(ANSI_COLOR_CYAN "################################################################################");
Logger::log(" Starting GLFW and OpenGL ");
Logger::log("################################################################################" ANSI_COLOR_RESET);
//Logger::show =false;
show3d=false;
glfwSetErrorCallback(OnError);
if(!glfwInit())
throw std::runtime_error("glfwInit failed");
// open a window with GLFW
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
gWindow = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "OpenGL Tutorial", NULL, NULL);
//Set Window Position or center of screen if not specified
if(argc >2 && atoi(argv[1]) != -1 && atoi(argv[2]) != -1){
glfwSetWindowPos(gWindow,atoi(argv[1]),atoi(argv[2]));
}
//Disallow Resizing
glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);
if(!gWindow)
throw std::runtime_error("glfwCreateWindow failed. Can your hardware handle OpenGL 4.1?");
// GLFW settings
glfwMakeContextCurrent(gWindow);
// initialise GLEW with core
glewExperimental = GL_TRUE;
if(glewInit() != GLEW_OK)
throw std::runtime_error("glewInit failed");
// print out some environment info
printInfo();
createShaders();
triangleSetup();
//Hide things that are behind others
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
//start timer
timer = 0.0;
//Create a screen size uniform
GLuint location = glGetUniformLocation(program->getID(),"screen");
glUniform2f(location,SCREEN_WIDTH, SCREEN_HEIGHT);
//Handle Key events
glfwSetKeyCallback(gWindow, key_press);
//Run Loop
while(!glfwWindowShouldClose(gWindow)){
glfwPollEvents();
Render();
}
glfwTerminate();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
struct ModelInputData
{
double start_army_size; // > 0 Tamanho inicial do exército
double start_enemy_size; // > 0 Tamanho inicial do exército inimigo
double loose_battle_fraction; // 0 < x < 1: Porcentagem do exército que define derrota
double army_skill; // 0 < x <= 1 Perícia do exército em eliminar inimigos
double enemy_skill; // 0 < x <= 1 Perícia do inimigo em eliminar o exército
double start_ammo; // > 0 Quantidade de munição que estará disponível durante a batalha
double army_fire_rate; // 0 < x <= 1 Taxa com que o exército consegue atirar a munição disponível
double ammo_diffusion_coeffient; // > 0 Velocidade com o que a munição é distribuída para o exército
double formation_size; // > 0 Tamanho da formação utilizada na batalha pelo exército
double front_line_fraction; // 0 < x <= 1 Porcentagem do exército que atuará na linha de frente
double enemy_front_line_fraction; // 0 < x <= 1 Porcentagem do exército inimigo que atuará na linha de frente
double delta_time; // > 0
double delta_x; // > 0
/**
* @brief ModelInputData default input data
*/
ModelInputData()
{
start_army_size = 500.0;
start_enemy_size = 500.0;
loose_battle_fraction = 0.01;
army_skill = 0.03;
enemy_skill = 0.03;
start_ammo = 950;
army_fire_rate = 0.05;
ammo_diffusion_coeffient = 1.0;
formation_size = 7;
front_line_fraction = 0.1;
enemy_front_line_fraction = 1.0;
delta_time = 0.07;
delta_x = 0.6;
std::cout << "CFL = " << ammo_diffusion_coeffient * delta_time / (delta_x * delta_x) << std::endl;
}
friend std::ostream& operator<< (std::ostream& out, const ModelInputData& input_data)
{
out << "#-------------------------------------------------" << std::endl;
out << "#--- GentlesmanBattle Input Data" << std::endl;
out << "#-------------------------------------------------" << std::endl;
out << "#- Start Army Size : " << input_data.start_army_size << std::endl;
out << "#- Start Enemy Size : " << input_data.start_enemy_size << std::endl;
out << "#- Army Skill : " << input_data.army_skill << std::endl;
out << "#- Enemy Skill : " << input_data.enemy_skill << std::endl;
out << "#- Start Ammo : " << input_data.start_ammo << std::endl;
out << "#- Ammo Diffusion Coef: " << input_data.ammo_diffusion_coeffient << std::endl;
out << "#- Battle Field Size : " << input_data.formation_size << std::endl;
out << "#- Front Line Fraction: " << input_data.front_line_fraction << std::endl;
out << "#- Delta Time : " << input_data.delta_time << std::endl;
out << "#- Delta X : " << input_data.delta_x << std::endl;
out << "#--------------------------------------------------" << std::endl;
return out;
}
};
struct ModelInfo
{
double time = 0.0;
double new_army_size = 0.0;
double old_army_size = 0.0;
double new_enemy_size = 0.0;
double old_enemy_size = 0.0;
std::vector<double> new_ammo_amount;
std::vector<double> old_ammo_amount;
const ModelInputData& model_input;
const double CFL = model_input.ammo_diffusion_coeffient * model_input.delta_time / (model_input.delta_x * model_input.delta_x);
ModelInfo(const ModelInputData& input_data) :
model_input(input_data)
{
// Setting up the mesh for the ammo diffusion
new_ammo_amount.resize(static_cast<int>(input_data.formation_size / input_data.delta_x));
old_ammo_amount.resize(new_ammo_amount.size());
// Initial condition
old_army_size = input_data.start_army_size;
old_enemy_size = input_data.start_enemy_size;
// Ammot starts at rear-line
old_ammo_amount[1] = model_input.start_ammo;
}
void advance_time()
{
// Calculates the fraction of the army and enemies currently standing in the front-line
double front_line_size = model_input.front_line_fraction * old_army_size;
double enemy_front_line_size = model_input.front_line_fraction * old_enemy_size;
// Army
new_army_size = old_army_size - model_input.delta_time * model_input.enemy_skill * front_line_size * enemy_front_line_size;
old_army_size = new_army_size;
// Enemy
double shoots_fired = old_ammo_amount.back() * model_input.army_fire_rate;
new_enemy_size = old_enemy_size - model_input.delta_time * model_input.army_skill * shoots_fired * front_line_size * enemy_front_line_size;
old_enemy_size = new_enemy_size;
// Ammo Diffusion
for(size_t i = 1; i < new_ammo_amount.size() - 1; ++i)
{
new_ammo_amount[i] = old_ammo_amount[i] + CFL * (old_ammo_amount[i-1] - 2.0 * old_ammo_amount[i] + old_ammo_amount[i+1]);
}
//
// Ammo boundary conditions
//
// At x=0 there is no flow.
new_ammo_amount[0] = new_ammo_amount[1];
// At x=L the ammo is being used by the soldiers
// Calculates the percentage of ammo used at the frontline.
double ammo_usage_ratio = 1.0 - (1.0 / front_line_size);
new_ammo_amount.back() = new_ammo_amount[new_ammo_amount.size() - 2] * ammo_usage_ratio;
// Swap vectors for next time step
new_ammo_amount.swap(old_ammo_amount);
// Finally, advance the time
time += model_input.delta_time;
}
/**
* @brief True if the battle has came to an end
*
* The condition for the battle to stop is when the army size reaches a fraction defined
* by @ref ModelInputData::loose_battle_fraction. The condition is applied for both the army
* and the enemies.
*
* @return True if the battle has came to an end false otherwise
*/
bool should_stop() const
{
return new_army_size <= model_input.start_army_size * model_input.loose_battle_fraction ||
new_enemy_size <= model_input.start_enemy_size * model_input.loose_battle_fraction;
}
/**
* @brief Returns true if the number of soldiers is bigger than the number of enemies soldiers at this moment
*/
bool is_army_winning() const
{
return old_army_size > old_enemy_size;
}
friend std::ostream& operator<< (std::ostream& out, const ModelInfo& info)
{
out << "#-------------------------------------------------" << std::endl;
out << "#--- GentlesmanBattle Execution Summary" << std::endl;
out << "#-------------------------------------------------" << std::endl;
out << "# Number of Iterations : " << info.time / info.model_input.delta_time << std::endl;
out << "# Total time : " << info.time << std::endl;
out << "# Soldiers Count : " << info.new_army_size << std::endl;
out << "# Enemies Count : " << info.new_enemy_size << std::endl;
out << "# Available Ammo at Fronline: " << info.new_ammo_amount.back() << std::endl;
out << "# Available Ammo at Rearline: " << info.new_ammo_amount.front() << std::endl;
out << "#-------------------------------------------------" << std::endl;
out << "# Battle Result: ";
if(info.is_army_winning())
{
out << "YOU WIN!" << std::endl;
}
else
{
out << "YOU LOOSE!" << std::endl;
}
out << "#-------------------------------------------------" << std::endl;
return out;
}
};
struct ModelOutput
{
std::string model_output_filename;
std::fstream output_file;
const ModelInfo& model_info;
ModelOutput(const std::string& prefix, const ModelInfo& _model_info, const ModelInputData& model_input)
: model_output_filename(prefix + "_gentlemans_battle.dat"),
model_info(_model_info)
{
output_file.open(model_output_filename, std::ios::out);
output_file << model_input << std::endl << std::endl;
output_file << "# Time ArmySize EnemySize" << std::endl;
}
void write_output_step()
{
output_file << std::setw(10) << std::setprecision(10) << std::fixed << std::setfill('0') <<
model_info.time << " " <<
model_info.old_army_size << " " <<
model_info.old_enemy_size << " " <<
model_info.old_ammo_amount.front() << " " <<
model_info.old_ammo_amount.back() << " " <<
std::endl;
}
void stop_execution(bool b_show_gnuplot = true)
{
// Write Execution Summary into the output file
output_file << model_info << std::endl;
if(output_file.is_open())
{
output_file.close();
}
if(b_show_gnuplot)
{
std::string output_filename_quotes = "'" + model_output_filename + "'";
std::string gnuplot_script_filename = "_gentlemans_battle.gnu";
std::fstream gnuplot_script_file(gnuplot_script_filename, std::ios::out);
gnuplot_script_file << "set xlabel 'Time'" << std::endl;
gnuplot_script_file << "set ylabel";
std::string plot_command = "gnuplot -p -e \"plot " +
output_filename_quotes + " using 1:2 with lines title 'Army'," +
output_filename_quotes + " using 1:3 with lines title 'Enemies'," +
output_filename_quotes + "using 1:4 with lines title 'Ammo at rearguard'," +
output_filename_quotes + "using 1:5 with lines title 'Ammo at frontline'" +
"\"";
std::cout << plot_command << std::endl;
// show reaction plot
system(plot_command.data());
// show diffusion plot
plot_command = "gnuplot -p -e \"plot " +
output_filename_quotes + "using 1:4 with lines title 'Ammo at rearguard'," +
output_filename_quotes + "using 1:5 with lines title 'Ammo at frontline'" +
"\"";
// system(plot_command.data());
std::cout << plot_command << std::endl;
}
}
};
struct GentlesmanBattleModel
{
ModelInputData input;
ModelOutput output;
ModelInfo info;
GentlesmanBattleModel() :
output("", info, input), info(input)
{
}
void run()
{
// Print parameters information
std::cout << input << std::endl;
do
{
output.write_output_step();
info.advance_time();
}
while(!info.should_stop());
// Print execution summary
std::cout << info << std::endl;
}
};
int main()
{
GentlesmanBattleModel model;
model.run();
model.output.stop_execution();
return EXIT_SUCCESS;
}
<commit_msg>Configuração do plot de reação<commit_after>#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
struct ModelInputData
{
double start_army_size; // > 0 Tamanho inicial do exército
double start_enemy_size; // > 0 Tamanho inicial do exército inimigo
double loose_battle_fraction; // 0 < x < 1: Porcentagem do exército que define derrota
double army_skill; // 0 < x <= 1 Perícia do exército em eliminar inimigos
double enemy_skill; // 0 < x <= 1 Perícia do inimigo em eliminar o exército
double start_ammo; // > 0 Quantidade de munição que estará disponível durante a batalha
double army_fire_rate; // 0 < x <= 1 Taxa com que o exército consegue atirar a munição disponível
double ammo_diffusion_coeffient; // > 0 Velocidade com o que a munição é distribuída para o exército
double formation_size; // > 0 Tamanho da formação utilizada na batalha pelo exército
double front_line_fraction; // 0 < x <= 1 Porcentagem do exército que atuará na linha de frente
double enemy_front_line_fraction; // 0 < x <= 1 Porcentagem do exército inimigo que atuará na linha de frente
double delta_time; // > 0
double delta_x; // > 0
/**
* @brief ModelInputData default input data
*/
ModelInputData()
{
start_army_size = 500.0;
start_enemy_size = 500.0;
loose_battle_fraction = 0.01;
army_skill = 0.03;
enemy_skill = 0.03;
start_ammo = 950;
army_fire_rate = 0.05;
ammo_diffusion_coeffient = 1.0;
formation_size = 7;
front_line_fraction = 0.1;
enemy_front_line_fraction = 1.0;
delta_time = 0.07;
delta_x = 0.6;
std::cout << "CFL = " << ammo_diffusion_coeffient * delta_time / (delta_x * delta_x) << std::endl;
}
friend std::ostream& operator<< (std::ostream& out, const ModelInputData& input_data)
{
out << "#-------------------------------------------------" << std::endl;
out << "#--- GentlesmanBattle Input Data" << std::endl;
out << "#-------------------------------------------------" << std::endl;
out << "#- Start Army Size : " << input_data.start_army_size << std::endl;
out << "#- Start Enemy Size : " << input_data.start_enemy_size << std::endl;
out << "#- Army Skill : " << input_data.army_skill << std::endl;
out << "#- Enemy Skill : " << input_data.enemy_skill << std::endl;
out << "#- Start Ammo : " << input_data.start_ammo << std::endl;
out << "#- Ammo Diffusion Coef: " << input_data.ammo_diffusion_coeffient << std::endl;
out << "#- Battle Field Size : " << input_data.formation_size << std::endl;
out << "#- Front Line Fraction: " << input_data.front_line_fraction << std::endl;
out << "#- Delta Time : " << input_data.delta_time << std::endl;
out << "#- Delta X : " << input_data.delta_x << std::endl;
out << "#--------------------------------------------------" << std::endl;
return out;
}
};
struct ModelInfo
{
double time = 0.0;
double new_army_size = 0.0;
double old_army_size = 0.0;
double new_enemy_size = 0.0;
double old_enemy_size = 0.0;
std::vector<double> new_ammo_amount;
std::vector<double> old_ammo_amount;
const ModelInputData& model_input;
const double CFL = model_input.ammo_diffusion_coeffient * model_input.delta_time / (model_input.delta_x * model_input.delta_x);
ModelInfo(const ModelInputData& input_data) :
model_input(input_data)
{
// Setting up the mesh for the ammo diffusion
new_ammo_amount.resize(static_cast<int>(input_data.formation_size / input_data.delta_x));
old_ammo_amount.resize(new_ammo_amount.size());
// Initial condition
old_army_size = input_data.start_army_size;
old_enemy_size = input_data.start_enemy_size;
// Ammot starts at rear-line
old_ammo_amount[1] = model_input.start_ammo;
}
void advance_time()
{
// Calculates the fraction of the army and enemies currently standing in the front-line
double front_line_size = model_input.front_line_fraction * old_army_size;
double enemy_front_line_size = model_input.front_line_fraction * old_enemy_size;
// Army
new_army_size = old_army_size - model_input.delta_time * model_input.enemy_skill * front_line_size * enemy_front_line_size;
old_army_size = new_army_size;
// Enemy
double shoots_fired = old_ammo_amount.back() * model_input.army_fire_rate;
new_enemy_size = old_enemy_size - model_input.delta_time * model_input.army_skill * shoots_fired * front_line_size * enemy_front_line_size;
old_enemy_size = new_enemy_size;
// Ammo Diffusion
for(size_t i = 1; i < new_ammo_amount.size() - 1; ++i)
{
new_ammo_amount[i] = old_ammo_amount[i] + CFL * (old_ammo_amount[i-1] - 2.0 * old_ammo_amount[i] + old_ammo_amount[i+1]);
}
//
// Ammo boundary conditions
//
// At x=0 there is no flow.
new_ammo_amount[0] = new_ammo_amount[1];
// At x=L the ammo is being used by the soldiers
// Calculates the percentage of ammo used at the frontline.
double ammo_usage_ratio = 1.0 - (1.0 / front_line_size);
new_ammo_amount.back() = new_ammo_amount[new_ammo_amount.size() - 2] * ammo_usage_ratio;
// Swap vectors for next time step
new_ammo_amount.swap(old_ammo_amount);
// Finally, advance the time
time += model_input.delta_time;
}
/**
* @brief True if the battle has came to an end
*
* The condition for the battle to stop is when the army size reaches a fraction defined
* by @ref ModelInputData::loose_battle_fraction. The condition is applied for both the army
* and the enemies.
*
* @return True if the battle has came to an end false otherwise
*/
bool should_stop() const
{
return new_army_size <= model_input.start_army_size * model_input.loose_battle_fraction ||
new_enemy_size <= model_input.start_enemy_size * model_input.loose_battle_fraction;
}
/**
* @brief Returns true if the number of soldiers is bigger than the number of enemies soldiers at this moment
*/
bool is_army_winning() const
{
return old_army_size > old_enemy_size;
}
friend std::ostream& operator<< (std::ostream& out, const ModelInfo& info)
{
out << "#-------------------------------------------------" << std::endl;
out << "#--- GentlesmanBattle Execution Summary" << std::endl;
out << "#-------------------------------------------------" << std::endl;
out << "# Number of Iterations : " << info.time / info.model_input.delta_time << std::endl;
out << "# Total time : " << info.time << std::endl;
out << "# Soldiers Count : " << info.new_army_size << std::endl;
out << "# Enemies Count : " << info.new_enemy_size << std::endl;
out << "# Available Ammo at Fronline: " << info.new_ammo_amount.back() << std::endl;
out << "# Available Ammo at Rearline: " << info.new_ammo_amount.front() << std::endl;
out << "#-------------------------------------------------" << std::endl;
out << "# Battle Result: ";
if(info.is_army_winning())
{
out << "YOU WIN!" << std::endl;
}
else
{
out << "YOU LOOSE!" << std::endl;
}
out << "#-------------------------------------------------" << std::endl;
return out;
}
};
struct ModelOutput
{
std::string model_output_filename;
std::fstream output_file;
const ModelInfo& model_info;
ModelOutput(const std::string& prefix, const ModelInfo& _model_info, const ModelInputData& model_input)
: model_output_filename(prefix + "_gentlemans_battle.dat"),
model_info(_model_info)
{
output_file.open(model_output_filename, std::ios::out);
output_file << model_input << std::endl << std::endl;
output_file << "# Time ArmySize EnemySize" << std::endl;
}
void write_output_step()
{
output_file << std::setw(10) << std::setprecision(10) << std::fixed << std::setfill('0') <<
model_info.time << " " <<
model_info.old_army_size << " " <<
model_info.old_enemy_size << " " <<
model_info.old_ammo_amount.front() << " " <<
model_info.old_ammo_amount.back() << " " <<
std::endl;
}
void stop_execution(bool b_show_gnuplot = true)
{
// Write Execution Summary into the output file
output_file << model_info << std::endl;
if(output_file.is_open())
{
output_file.close();
}
if(b_show_gnuplot)
{
std::string output_filename_quotes = "'" + model_output_filename + "'";
std::string gnuplot_script_filename = "_gentlemans_battle.gnu";
{
std::fstream gnuplot_script_file(gnuplot_script_filename, std::ios::out);
gnuplot_script_file << "set terminal 'wxt'" << std::endl;
gnuplot_script_file << "set xlabel 'Tempo'" << std::endl;
gnuplot_script_file << "set ylabel 'Número de Soldados'" << std::endl;
gnuplot_script_file << "set zeroaxis" << std::endl;
gnuplot_script_file << "set title 'Evolução do Número de Soldados no Campo de Batalha'" << std::endl;
gnuplot_script_file << "plot " <<
output_filename_quotes << " using 1:2 with lines title 'Soldados'," +
output_filename_quotes << " using 1:3 with lines title 'Inimigos'";
}
// show reaction plot
std::string plot_command = "gnuplot -p " + gnuplot_script_filename;
std::cout << plot_command << std::endl;
system(plot_command.data());
// show diffusion plot
// plot_command = "gnuplot -p -e \"plot " +
// output_filename_quotes + "using 1:4 with lines title 'Ammo at rearguard'," +
// output_filename_quotes + "using 1:5 with lines title 'Ammo at frontline'" +
// "\"";
//// system(plot_command.data());
// std::cout << plot_command << std::endl;
}
}
};
struct GentlesmanBattleModel
{
ModelInputData input;
ModelOutput output;
ModelInfo info;
GentlesmanBattleModel() :
output("", info, input), info(input)
{
}
void run()
{
// Print parameters information
std::cout << input << std::endl;
do
{
output.write_output_step();
info.advance_time();
}
while(!info.should_stop());
// Print execution summary
std::cout << info << std::endl;
}
};
int main()
{
GentlesmanBattleModel model;
model.run();
model.output.stop_execution();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <algorithm>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <cstring>
#include <cstddef>
using namespace std;
#define printVec(x) for(unsigned int i = 0; i < x.size(); i++) \
cout << x.at(i) << " "; \
cout << endl;
//function to print out the contents of argv
void printARGV(char **argv){
int i = 0;
while(argv[i] != NULL){
cout << "Pos " << i << ": " << argv[i] << endl;
i++;
}
cout << endl;
}
/*this function will get all the file descriptors or directories and put
them into a vector of strings called file_O_dir*/
//anything that is not 'ls' or '-<flags>' is considered a file or dir
vector<string> getFiles_Dirs (char **argv){
string targets; //this is the rest of the targest after the flags
string ls = "ls";
char dash = '-';
vector<string> importantStuff;
unsigned int pos = 1;
while(argv[pos] != '\0'){
string temp = argv[pos]; //keep the current argv part in a string
if(argv[pos] == ls){
pos++; //increment position to get next arg
continue; //continue to next iteration
}
if(argv[pos][0] == dash){
pos++; //increment position to get next arg
continue; //continue to next iteration
}
importantStuff.push_back(temp); //if both cases fail, you add it!
pos++; //increment to get next arg
}
return importantStuff;
}
/*Comparision function for two char* */
/*needed for sorting*/
bool compareTwo(const char* s1, const char* s2){
return strcasecmp(s1, s2) < 0;
}
bool compareTwo_(string a, string b){
string str1( a );
string str2( b );
transform( str1.begin(), str1.end(), str1.begin(), ::tolower);
transform( str2.begin(), str2.end(), str2.begin(), ::tolower);
return (str1 < str2);
}
/*this function takes in a directory and outputs its contents*/
/*string magic = directory */
vector<char*> open_direct(string magic){
const char* magic_2 = magic.c_str(); //need to do some more magic
vector<char*> filenames; //to store the filenames so we can sort
DIR *dirp;
if(NULL == (dirp = opendir(magic_2))){
perror("There was an error with opendir(). ");
exit(1);
}
struct dirent *filespecs;
errno = 0;
while(NULL != (filespecs = readdir(dirp))){
filenames.push_back(filespecs->d_name);
//cout << filespecs->d_name << " ";
}
if(errno != 0){
perror("There was an error with readdir(). ");
exit(1);
}
cout << endl;
if(-1 == closedir(dirp)){
perror("There was an error with closedir(). ");
exit(1);
}
return filenames;
}
int main(int argc, char**argv){
//test and case variables
string flags_;
string ls = "ls";
char dash = '-';
// --------------------------------------------------------------------
//vectors of flags -a, -l, -R
vector<char> flags;
flags.push_back('a');
flags.push_back('l');
flags.push_back('R');
//vector of files & directories
vector<string> files_dirs;
// --------------------------------------------------------------------
bool isFlag_a = false; //bool to determine if the flag is -a
bool isFlag_l = false; //bool to determine if the flag is -l
bool isFlag_R = false; //bool to determine if the flag is -R
bool is_ls = false; //bool to determine if the input ONLY ls
// --------------------------------------------------------------------
if(argc <= 1){ //assumes the user didn't type anything
return 0;
}
// --------------------------------------------------------------------
//What's in char **argv?
//printARGV(argv);
// --------------------------------------------------------------------
/*if you type anything other than ls or ls with flags,
output an error and quit the program*/
if(argc > 1 && argc <= 2 && argv[1] != ls){
cout << "Error: no form of ls" << endl;
exit(1);
}
/*below are some cases for ls*/
else if(argc > 1 && argv[1] == ls){ //is there a ls?
is_ls = true;
if(is_ls) ;
files_dirs = getFiles_Dirs(argv); //get directories or files
sort(files_dirs.begin(), files_dirs.end(), compareTwo_);
printVec(files_dirs);
//where there any directories or files that were called?
if( !(files_dirs.size() > 0) ){
/*call ls on the current working directory*/
//get the current working directory
char buf[1024];
if(!getcwd(buf,1024)){
perror("problem with getcwd");
}
string cwd(buf); //convert cstring to string for function
//get the vector of the contents in the current directory
vector<char*> contents = open_direct(cwd);
/*remove any hidden files (files that begin with a '.')*/
char dot = '.';
unsigned int totalsize = contents.size();
for(unsigned int i = 0; i < totalsize; ++i){
if(*(contents.at(i)) == dot){
contents.erase(contents.begin() + i); //remove that file
totalsize--; //after you erase you -1 from size
i = 0; //after you -1 from size, you reset i
}
}
//sort the files within directory
sort(contents.begin(), contents.end(), compareTwo);
//print the files to standard out
printVec(contents);
}
else{
;
}
}
else{ //is there a ls with flags and maybe files or dir
for(int x = 0; x < argc; ++x){
if(*(argv[x]) == dash){ //grabs flags
flags_ = argv[x]; //put the cstring in a string
flags_.erase(flags_.begin()); //erase the '-' at the beginning
//go through each flag_ and compare with the vector of flags
for(unsigned int i = 0 ; i < flags_.size(); ++i){
for(unsigned int j = 0; j < flags.size(); ++j){
if(flags_.at(i) == flags.at(j)){
if(flags.at(j) == 'a'){
isFlag_a = true;
if(isFlag_a) cout << "We have a!" << endl;
}
else if(flags.at(j) == 'l'){
isFlag_l = true;
if(isFlag_l) cout << "We have l!" << endl;
}
else if(flags.at(j) == 'R'){
isFlag_R = true;
if(isFlag_R) cout << "We have R!" << endl;
}
}
}
}
}
}
}
//files_dirs = getFiles_Dir(argv, );
// --------------------------------------------------------------------
return 0;
}
<commit_msg>working on ls with multiple files<commit_after>#include <iostream>
#include <algorithm>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <cstring>
#include <cstddef>
using namespace std;
#define printVec(x) for(unsigned int i = 0; i < x.size(); i++) \
cout << x.at(i) << " "; \
cout << endl;
//function to print out the contents of argv
void printARGV(char **argv){
int i = 0;
while(argv[i] != NULL){
cout << "Pos " << i << ": " << argv[i] << endl;
i++;
}
cout << endl;
}
/*this function will get all the file descriptors or directories and put
them into a vector of strings called file_O_dir*/
//anything that is not 'ls' or '-<flags>' is considered a file or dir
vector<string> getFiles_Dirs (char **argv){
string targets; //this is the rest of the targest after the flags
string ls = "ls";
char dash = '-';
vector<string> importantStuff;
unsigned int pos = 1;
while(argv[pos] != '\0'){
string temp = argv[pos]; //keep the current argv part in a string
if(argv[pos] == ls){
pos++; //increment position to get next arg
continue; //continue to next iteration
}
if(argv[pos][0] == dash){
pos++; //increment position to get next arg
continue; //continue to next iteration
}
importantStuff.push_back(temp); //if both cases fail, you add it!
pos++; //increment to get next arg
}
return importantStuff;
}
/*Comparision function for two char* */
/*needed for sorting*/
bool compareTwo(const char* s1, const char* s2){
return strcasecmp(s1, s2) < 0;
}
bool compareTwo_(string a, string b){
string str1( a );
string str2( b );
transform( str1.begin(), str1.end(), str1.begin(), ::tolower);
transform( str2.begin(), str2.end(), str2.begin(), ::tolower);
return (str1 < str2);
}
/*this function takes in a directory and outputs its contents*/
/*string magic = directory */
vector<char*> open_direct(string magic){
const char* magic_2 = magic.c_str(); //need to do some more magic
vector<char*> filenames; //to store the filenames so we can sort
DIR *dirp;
if(NULL == (dirp = opendir(magic_2))){
perror("There was an error with opendir(). ");
exit(1);
}
struct dirent *filespecs;
errno = 0;
while(NULL != (filespecs = readdir(dirp))){
filenames.push_back(filespecs->d_name);
//cout << filespecs->d_name << " ";
}
if(errno != 0){
perror("There was an error with readdir(). ");
exit(1);
}
cout << endl;
if(-1 == closedir(dirp)){
perror("There was an error with closedir(). ");
exit(1);
}
return filenames;
}
void ls_multiple(vector<string> &file_dir){
for(unsigned int i = 0; i < file_dir.size(); ++i){
unsigned int j;
//CHECK THIS STATEMENT!!!
vector<char*> contents_ = open_direct((file_dir.at(i)));
/*remove any hidden files (files that begin with a '.')*/
char dot = '.';
unsigned int totalsize = contents_.size();
for(j = 0; j < totalsize; ++j){
if(*(contents_.at(j)) == dot){
contents_.erase(contents_.begin() + j); //remove that file
totalsize--; //after you erase you -1 from size
j = 0; //after you -1 from size, you reset i
}
}
//sort the files within directory
sort(contents_.begin(), contents_.end(), compareTwo);
cout << file_dir.at(j) << ":" << endl; //formatting..
//print the files to standard out
printVec(contents_);
cout << endl; //formatting..
}
}
int main(int argc, char**argv){
//test and case variables
string flags_;
string ls = "ls";
char dash = '-';
// --------------------------------------------------------------------
//vectors of flags -a, -l, -R
vector<char> flags;
flags.push_back('a');
flags.push_back('l');
flags.push_back('R');
//vector of files & directories
vector<string> files_dirs;
// --------------------------------------------------------------------
bool isFlag_a = false; //bool to determine if the flag is -a
bool isFlag_l = false; //bool to determine if the flag is -l
bool isFlag_R = false; //bool to determine if the flag is -R
bool is_ls = false; //bool to determine if the input ONLY ls
// --------------------------------------------------------------------
if(argc <= 1){ //assumes the user didn't type anything
return 0;
}
// --------------------------------------------------------------------
//What's in char **argv?
//printARGV(argv);
// --------------------------------------------------------------------
/*if you type anything other than ls or ls with flags,
output an error and quit the program*/
if(argc > 1 && argc <= 2 && argv[1] != ls){
cout << "Error: no form of ls" << endl;
exit(1);
}
/*below are some cases for ls*/
else if(argc > 1 && argv[1] == ls){ //is there a ls?
is_ls = true;
if(is_ls) ;
files_dirs = getFiles_Dirs(argv); //get directories or files
//sort dictionary files so they can be executed in order
sort(files_dirs.begin(), files_dirs.end(), compareTwo_);
//where there any directories or files that were called?
if( !(files_dirs.size() > 0) ){
/*call ls on the current working directory*/
//get the current working directory
char buf[1024];
if(!getcwd(buf,1024)){
perror("problem with getcwd");
}
string cwd(buf); //convert cstring to string for function
//get the vector of the contents in the current directory
vector<char*> contents = open_direct(cwd);
/*remove any hidden files (files that begin with a '.')*/
char dot = '.';
unsigned int totalsize = contents.size();
for(unsigned int i = 0; i < totalsize; ++i){
if(*(contents.at(i)) == dot){
contents.erase(contents.begin() + i); //remove that file
totalsize--; //after you erase you -1 from size
i = 0; //after you -1 from size, you reset i
}
}
//sort the files within directory
sort(contents.begin(), contents.end(), compareTwo);
//print the files to standard out
printVec(contents);
}
else{
files_dirs = getFiles_Dirs(argv);
ls_multiple(files_dirs);
}
}
else{ //is there a ls with flags and maybe files or dir
for(int x = 0; x < argc; ++x){
if(*(argv[x]) == dash){ //grabs flags
flags_ = argv[x]; //put the cstring in a string
flags_.erase(flags_.begin()); //erase the '-' at the beginning
//go through each flag_ and compare with the vector of flags
for(unsigned int i = 0 ; i < flags_.size(); ++i){
for(unsigned int j = 0; j < flags.size(); ++j){
if(flags_.at(i) == flags.at(j)){
if(flags.at(j) == 'a'){
isFlag_a = true;
if(isFlag_a) cout << "We have a!" << endl;
}
else if(flags.at(j) == 'l'){
isFlag_l = true;
if(isFlag_l) cout << "We have l!" << endl;
}
else if(flags.at(j) == 'R'){
isFlag_R = true;
if(isFlag_R) cout << "We have R!" << endl;
}
}
}
}
}
}
}
//files_dirs = getFiles_Dir(argv, );
// --------------------------------------------------------------------
return 0;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbConnectedComponentSegmentation.h"
#include <iostream>
#include "otbCommandLineArgumentParser.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include "itkExceptionObject.h"
#include "otbImage.h"
#include "otbMath.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbParser.h"
#include "itkRelabelComponentImageFilter.h"
#include <itkLabelMap.h>
#include <otbLabelMapWithAdjacency.h>
//#include <itkLabelImageToLabelMapFilter.h>
#include <otbLabelImageToLabelMapWithAdjacencyFilter.h>
#include <itkScalarToRGBPixelFunctor.h>
#include <itkUnaryFunctorImageFilter.h>
#include "otbConnectedComponentMuParserFunctor.h"
#include <itkConnectedComponentFunctorImageFilter.h>
#include "otbMaskMuParserFilter.h"
#include <otbAttributesMapLabelObject.h>
#include <itkAttributeLabelObject.h>
#include "otbBandsStatisticsAttributesLabelMapFilter.h"
#include <itkStatisticsLabelObject.h>
#include <itkShapeLabelMapFilter.h>
#include <otbShapeAttributesLabelMapFilter.h>
#include <itkLabelObject.h>
#include "itkLabelImageToShapeLabelMapFilter.h"
#include <iostream>
#include "otbLabelObjectOpeningMuParserFilter.h"
//#include <itkLabelMapToRGBImageFilter.h>
#include <itkLabelMapToLabelImageFilter.h>
#include "otbVectorDataProjectionFilter.h"
#include "otbVectorData.h"
#include "otbVectorDataFileWriter.h"
#include "itkPreOrderTreeIterator.h"
#include <otbLabelMapToVectorDataFilter.h>
namespace otb
{
typedef float InputPixelType;
const unsigned int Dimension = 2;
typedef itk::RGBPixel<unsigned char> RGBPixelType;
typedef otb::Image<RGBPixelType, 2> RGBImageType;
typedef otb::ImageFileWriter<RGBImageType> RGBWriterType;
//conected component typedef
typedef otb::VectorImage<InputPixelType, Dimension> InputVectorImageType;
typedef otb::ImageFileReader<InputVectorImageType> ReaderType;
typedef otb::Image<unsigned int, Dimension> InputMaskImageType;
typedef otb::ImageFileReader<InputMaskImageType> MaskReaderType;
typedef otb::Image<unsigned int, Dimension> OutputImageType;
typedef otb::Image<unsigned int, Dimension> LabelImageType;
typedef otb::ImageFileWriter<OutputImageType> WriterType;
typedef Functor::ConnectedComponentMuParserFunctor<InputVectorImageType::PixelType> FunctorType;
typedef itk::ConnectedComponentFunctorImageFilter<InputVectorImageType, OutputImageType, FunctorType, InputMaskImageType> ConnectedComponentFilterType;
// Labelization
typedef itk::RelabelComponentImageFilter<LabelImageType, LabelImageType> RelabelComponentFilterType;
typedef otb::AttributesMapLabelObject<unsigned int, Dimension, double> AttributesMapLabelObjectType;
typedef itk::AttributeLabelObject<unsigned int, Dimension, double> AttributesLabelObjectType;
typedef otb::LabelMapWithAdjacency<AttributesMapLabelObjectType> AttributesLabelMapType;
typedef otb::LabelImageToLabelMapWithAdjacencyFilter<LabelImageType, AttributesLabelMapType> LabelImageToLabelMapFilterType;
typedef otb::BandsStatisticsAttributesLabelMapFilter<AttributesLabelMapType, InputVectorImageType> RadiometricLabelMapFilterType;
typedef otb::ShapeAttributesLabelMapFilter<AttributesLabelMapType> ShapeLabelMapFilterType;
typedef itk::ShapeLabelObject<unsigned int, Dimension> ShapeLabelObjectType;
typedef itk::LabelObject<unsigned int, Dimension> LabelObjectType;
typedef itk::LabelMap<ShapeLabelObjectType> ShapeLabelMapType;
typedef itk::LabelImageToShapeLabelMapFilter<OutputImageType, ShapeLabelMapType> LabelImageToShapeLabelMapFilterType;
// colored label image typedef
typedef itk::Functor::ScalarToRGBPixelFunctor<unsigned long> ColorMapFunctorType;
typedef itk::UnaryFunctorImageFilter<OutputImageType, RGBImageType, ColorMapFunctorType> ColorMapFilterType;
// mask typedef
typedef otb::MaskMuParserFilter<InputVectorImageType, OutputImageType> MaskMuParserFilterType;
typedef otb::LabelObjectOpeningMuParserFilter<AttributesLabelMapType> LabelObjectOpeningFilterType;
typedef itk::LabelMapToLabelImageFilter<AttributesLabelMapType, OutputImageType> LabelMapToLabelImageFilterType;
/** Vector data handling */
typedef otb::VectorData<double, 2> VectorDataType;
typedef VectorDataType::Pointer VectorDataPointerType;
typedef otb::VectorDataFileWriter<VectorDataType> VectorDataFileWriterType;
typedef VectorDataFileWriterType::Pointer VectorDataFileWriterPointerType;
typedef otb::LabelMapToVectorDataFilter<AttributesLabelMapType, VectorDataType> LabelMapToVectorDataFilterType;
int ConnectedComponentSegmentation::Describe(ApplicationDescriptor* descriptor)
{
descriptor->SetName("Connected Component Segmentation");
descriptor->SetDescription("Connected Component Segmentation, which take mathematical formula as an Neighborhood thresholding criteria.");
descriptor->AddInputImage();
descriptor->AddOutputImage();
descriptor->AddOption("OutputShapeFileName", "Output Shape file name",
"outshape", 1, true, ApplicationDescriptor::FileName);
descriptor->AddOption("Expression", "Formula",
"expression", 1, true, ApplicationDescriptor::String);
descriptor->AddOption("MinSize", "Min object size (area in pixel)",
"minsize", 1, false, ApplicationDescriptor::Real);
descriptor->AddOption("InputImageMaskFileName", "Image for mask computation",
"inmask", 1, false, ApplicationDescriptor::InputImage);
descriptor->AddOption("MaskExpression", "Mask expression (only if support image is given)",
"maskexpression", 1, false, ApplicationDescriptor::String);
descriptor->AddOption("OBIAExpression", "OBIA Mu Parser expression",
"OBIAexpression", 1, true, ApplicationDescriptor::String);
descriptor->AddOption("IntermediateOutput", "Save intermediate output",
"dbg", 0, false, ApplicationDescriptor::Boolean);
return EXIT_SUCCESS;
}
int ConnectedComponentSegmentation::Execute(otb::ApplicationOptionsResult* parseResult)
{
ConnectedComponentFilterType::Pointer connected = ConnectedComponentFilterType::New();
// Read the input image
std::string inFileName = parseResult->GetParameterString("InputImage");
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(inFileName);
reader->UpdateOutputInformation();
connected->SetInput(reader->GetOutput());
MaskReaderType::Pointer maskReader;
ReaderType::Pointer maskImageReader;
MaskMuParserFilterType::Pointer maskFilter;
WriterType::Pointer writer = WriterType::New();
// Read the mask image
if(parseResult->IsOptionPresent("MaskExpression"))
{
std::string maskFileName;
if(parseResult->IsOptionPresent("InputImageMaskFileName"))
{
maskFileName = parseResult->GetParameterString("InputImageMaskFileName");
}
else // use image input
{
maskFileName = inFileName;
}
maskImageReader = ReaderType::New();
maskImageReader->SetFileName(maskFileName);
maskImageReader->UpdateOutputInformation();
maskFilter= MaskMuParserFilterType::New();
maskFilter->SetInput(maskImageReader->GetOutput());
std::string maskexpression = parseResult->GetParameterString("MaskExpression");
maskFilter->SetExpression(maskexpression);
maskFilter->UpdateOutputInformation();
if(parseResult->IsOptionPresent("IntermediateOutput"))
{
writer->SetInput(maskFilter->GetOutput());
writer->SetFileName("binaryMask.tif");
writer->Update();
}
connected->SetMaskImage(maskFilter->GetOutput());
}
else
if(parseResult->IsOptionPresent("InputImageMaskFileName"))
{
std::string maskFileName = parseResult->GetParameterString("InputImageMaskFileName");
maskReader = MaskReaderType::New();
maskReader->SetFileName(maskFileName);
maskReader->UpdateOutputInformation();
connected->SetMaskImage(maskReader->GetOutput());
}
// set up formula for connected component segmentation
std::string expression = parseResult->GetParameterString("Expression");
connected->GetFunctor().SetExpression(expression);
connected->Update();
if(parseResult->IsOptionPresent("IntermediateOutput"))
{
writer->SetInput(connected->GetOutput());
writer->SetFileName("connectedComponentLabelImage.tif");
writer->Update();
}
// relabel component
double minObjectSize;
if(parseResult->IsOptionPresent("MinSize"))
minObjectSize = parseResult->GetParameterDouble("MinSize");
else
minObjectSize=2;
// relabel connected component output
RelabelComponentFilterType::Pointer relabel = RelabelComponentFilterType::New();
relabel->SetInput(connected->GetOutput());
relabel->SetMinimumObjectSize(minObjectSize);
// debug output
if(parseResult->IsOptionPresent("IntermediateOutput"))
{
ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
colormapper->SetInput(relabel->GetOutput());
RGBWriterType::Pointer RGBwriter = RGBWriterType::New();
RGBwriter->SetInput(colormapper->GetOutput());
RGBwriter->SetFileName("RGBLabeledImage.tif");
RGBwriter->Update();
}
// step 3 transformation into labelmap and object characterization
//Attributes computation
// LabelImage to Label Map transformation
LabelImageToLabelMapFilterType::Pointer labelImageToLabelMap = LabelImageToLabelMapFilterType::New();
labelImageToLabelMap->SetInput(relabel->GetOutput());
labelImageToLabelMap->SetBackgroundValue(0);
// intermediate step : Fusion
// TBD
// shape attributes computation
ShapeLabelMapFilterType::Pointer shapeLabelMapFilter = ShapeLabelMapFilterType::New();
shapeLabelMapFilter->SetInput(labelImageToLabelMap->GetOutput());
shapeLabelMapFilter->SetReducedAttributeSet(false);
// band stat attributes computation
RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter
= RadiometricLabelMapFilterType::New();
radiometricLabelMapFilter->SetInput(shapeLabelMapFilter->GetOutput());
radiometricLabelMapFilter->SetNumberOfThreads(1);
radiometricLabelMapFilter->SetFeatureImage(reader->GetOutput());
radiometricLabelMapFilter->SetReducedAttributeSet(false);
radiometricLabelMapFilter->Update();
AttributesLabelMapType::Pointer AttributesLabelMap;
AttributesLabelMap=radiometricLabelMapFilter->GetOutput();
//AttributesLabelMap->SetAdjacencyMap(labelImageToLabelMap->GetOutput()->GetAdjacencyMap());
// TODO JGU code clean is necessary
// DBG OUTPUT
//unsigned int nb_obj=AttributesLabelMap->GetNumberOfLabelObjects();
//std::cout<<"number of attributes map label objects : "<<nb_obj<<std::endl;
// step 4 OBIA Filtering using shape and radiometric object characteristics
std::string OBIAexpression = parseResult->GetParameterString("OBIAExpression");
LabelObjectOpeningFilterType::Pointer opening= LabelObjectOpeningFilterType::New();
opening->SetExpression(OBIAexpression);
opening->SetInput( radiometricLabelMapFilter->GetOutput());
opening->Update();
LabelMapToLabelImageFilterType::Pointer labelMapToLabelImage = LabelMapToLabelImageFilterType::New();
labelMapToLabelImage->SetInput(opening->GetOutput());
labelMapToLabelImage->Update();
if(parseResult->IsOptionPresent("IntermediateOutput"))
{
ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
colormapper->SetInput(labelMapToLabelImage->GetOutput());
RGBWriterType::Pointer RGBwriter = RGBWriterType::New();
RGBwriter->SetInput(colormapper->GetOutput());
RGBwriter->SetFileName("RGBOpeningOutput.tif");
RGBwriter->Update();
// removed object dbg output
LabelMapToLabelImageFilterType::Pointer labelMapToLabelImageRemoved = LabelMapToLabelImageFilterType::New();
labelMapToLabelImageRemoved->SetInput(opening->GetOutput(1));
labelMapToLabelImageRemoved->Update();
//ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
colormapper->SetInput(labelMapToLabelImageRemoved->GetOutput());
//RGBWriterType::Pointer RGBwriter = RGBWriterType::New();
RGBwriter->SetInput(colormapper->GetOutput());
RGBwriter->SetFileName("RGBOpeningRemovedObjects.tif");
RGBwriter->Update();
}
//TODO JGU : code cleanup is needed
//std::cout<<" new object number after opening : "<<opening->GetOutput()->GetNumberOfLabelObjects()<<std::endl;
//std::cout<<" removed objects : "<<opening->GetOutput(1)->GetNumberOfLabelObjects()<<std::endl;
//step 5 : Vectorization
LabelMapToVectorDataFilterType::Pointer labelMapToVectorDataFilter = LabelMapToVectorDataFilterType::New();
labelMapToVectorDataFilter->SetInput(opening->GetOutput());
labelMapToVectorDataFilter->Update();
VectorDataPointerType vectorData=labelMapToVectorDataFilter->GetOutput();
// Instantiate the vdwriter
std::string vdoutFilename = parseResult->GetParameterString("OutputShapeFileName");
VectorDataFileWriterPointerType vdwriter = VectorDataFileWriterType::New();
vdwriter->SetInput(vectorData);
vdwriter->SetFileName(vdoutFilename);
vdwriter->Update();
// Instantiate the writer
std::string outFilename = parseResult->GetParameterString("OutputImage");
writer->SetInput(labelMapToLabelImage->GetOutput());
writer->SetFileName(outFilename);
writer->Update();
return EXIT_SUCCESS;
}
}
<commit_msg>STYLE Code cleanup<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbConnectedComponentSegmentation.h"
#include <iostream>
#include "otbCommandLineArgumentParser.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include "itkExceptionObject.h"
#include "otbImage.h"
#include "otbMath.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbParser.h"
#include "itkRelabelComponentImageFilter.h"
#include <itkLabelMap.h>
#include <otbLabelMapWithAdjacency.h>
#include <otbLabelImageToLabelMapWithAdjacencyFilter.h>
#include <itkScalarToRGBPixelFunctor.h>
#include <itkUnaryFunctorImageFilter.h>
#include "otbConnectedComponentMuParserFunctor.h"
#include <itkConnectedComponentFunctorImageFilter.h>
#include "otbMaskMuParserFilter.h"
#include <otbAttributesMapLabelObject.h>
#include <itkAttributeLabelObject.h>
#include "otbBandsStatisticsAttributesLabelMapFilter.h"
#include <itkStatisticsLabelObject.h>
#include <itkShapeLabelMapFilter.h>
#include <otbShapeAttributesLabelMapFilter.h>
#include <itkLabelObject.h>
#include "itkLabelImageToShapeLabelMapFilter.h"
#include <iostream>
#include "otbLabelObjectOpeningMuParserFilter.h"
#include <itkLabelMapToLabelImageFilter.h>
#include "otbVectorDataProjectionFilter.h"
#include "otbVectorData.h"
#include "otbVectorDataFileWriter.h"
#include <otbLabelMapToVectorDataFilter.h>
namespace otb
{
typedef float InputPixelType;
const unsigned int Dimension = 2;
typedef itk::RGBPixel<unsigned char> RGBPixelType;
typedef otb::Image<RGBPixelType, 2> RGBImageType;
typedef otb::VectorImage<InputPixelType, Dimension> InputVectorImageType;
typedef otb::ImageFileReader<InputVectorImageType> ReaderType;
typedef otb::Image<unsigned int, Dimension> InputMaskImageType;
typedef otb::ImageFileReader<InputMaskImageType> MaskReaderType;
typedef otb::Image<unsigned int, Dimension> OutputImageType;
typedef otb::Image<unsigned int, Dimension> LabelImageType;
typedef otb::ImageFileWriter<OutputImageType> WriterType;
typedef otb::ImageFileWriter<RGBImageType> RGBWriterType;
typedef Functor::ConnectedComponentMuParserFunctor<InputVectorImageType::PixelType> FunctorType;
typedef itk::ConnectedComponentFunctorImageFilter<InputVectorImageType, LabelImageType, FunctorType, InputMaskImageType>
ConnectedComponentFilterType;
// Labelization
typedef itk::RelabelComponentImageFilter<LabelImageType, LabelImageType> RelabelComponentFilterType;
typedef otb::AttributesMapLabelObject<unsigned int, Dimension, double> AttributesMapLabelObjectType;
typedef itk::AttributeLabelObject<unsigned int, Dimension, double> AttributesLabelObjectType;
typedef otb::LabelMapWithAdjacency<AttributesMapLabelObjectType> AttributesLabelMapType;
typedef otb::LabelImageToLabelMapWithAdjacencyFilter<LabelImageType, AttributesLabelMapType>
LabelImageToLabelMapFilterType;
typedef otb::BandsStatisticsAttributesLabelMapFilter<AttributesLabelMapType, InputVectorImageType>
RadiometricLabelMapFilterType;
typedef otb::ShapeAttributesLabelMapFilter<AttributesLabelMapType> ShapeLabelMapFilterType;
typedef itk::ShapeLabelObject<unsigned int, Dimension> ShapeLabelObjectType;
typedef itk::LabelObject<unsigned int, Dimension> LabelObjectType;
typedef itk::LabelMap<ShapeLabelObjectType> ShapeLabelMapType;
typedef itk::LabelImageToShapeLabelMapFilter<OutputImageType, ShapeLabelMapType> LabelImageToShapeLabelMapFilterType;
// colored label image typedef
typedef itk::Functor::ScalarToRGBPixelFunctor<unsigned long> ColorMapFunctorType;
typedef itk::UnaryFunctorImageFilter<LabelImageType, RGBImageType, ColorMapFunctorType> ColorMapFilterType;
// mask typedef
typedef otb::MaskMuParserFilter<InputVectorImageType, OutputImageType> MaskMuParserFilterType;
typedef otb::LabelObjectOpeningMuParserFilter<AttributesLabelMapType> LabelObjectOpeningFilterType;
typedef itk::LabelMapToLabelImageFilter<AttributesLabelMapType, OutputImageType> LabelMapToLabelImageFilterType;
/** Vector data handling */
typedef otb::VectorData<double, Dimension> VectorDataType;
typedef VectorDataType::Pointer VectorDataPointerType;
typedef otb::VectorDataFileWriter<VectorDataType> VectorDataFileWriterType;
typedef VectorDataFileWriterType::Pointer VectorDataFileWriterPointerType;
typedef otb::LabelMapToVectorDataFilter<AttributesLabelMapType, VectorDataType> LabelMapToVectorDataFilterType;
int ConnectedComponentSegmentation::Describe(ApplicationDescriptor* descriptor)
{
descriptor->SetName("Connected Component Segmentation");
descriptor->SetDescription(
"Connected Component Segmentation, which take mathematical formula as an Neighborhood thresholding criteria.");
descriptor->AddOption("InputImageFileName", "Input frame file name", "in", 1, true, ApplicationDescriptor::FileName);
descriptor->AddOption("OutputFileName", "Output file name", "out", 1, true, ApplicationDescriptor::FileName);
descriptor->AddOption("OutputShapeFileName", "Output Shape file name", "outshape", 1, true,
ApplicationDescriptor::FileName);
descriptor->AddOption("Expression", "Formula", "expression", 1, true, ApplicationDescriptor::String);
descriptor->AddOption("MinSize", "Min object size (area in pixel)", "minsize", 1, false, ApplicationDescriptor::Real);
descriptor->AddOption("InputImageMaskFileName", "Image for mask computation", "inmask", 1, false,
ApplicationDescriptor::FileName);
descriptor->AddOption("MaskExpression", "Mask expression (only if support image is given)", "maskexpression", 1,
false, ApplicationDescriptor::String);
descriptor->AddOption("OBIAExpression", "OBIA Mu Parser expression", "OBIAexpression", 1, true,
ApplicationDescriptor::String);
descriptor->AddOption("IntermediateOutput", "Save intermediate output", "dbg", 0, false,
ApplicationDescriptor::Boolean);
return EXIT_SUCCESS;
}
int ConnectedComponentSegmentation::Execute(otb::ApplicationOptionsResult* parseResult)
{
ConnectedComponentFilterType::Pointer connected = ConnectedComponentFilterType::New();
// Read the input image
std::string inFileName = parseResult->GetParameterString("InputImageFileName");
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(inFileName);
reader->UpdateOutputInformation();
connected->SetInput(reader->GetOutput());
MaskReaderType::Pointer maskReader;
ReaderType::Pointer maskImageReader;
MaskMuParserFilterType::Pointer maskFilter;
WriterType::Pointer writer = WriterType::New();
// Read the mask image
if (parseResult->IsOptionPresent("MaskExpression"))
{
std::string maskFileName;
if (parseResult->IsOptionPresent("InputImageMaskFileName"))
{
maskFileName = parseResult->GetParameterString("InputImageMaskFileName");
}
else // use image input
{
maskFileName = inFileName;
}
maskImageReader = ReaderType::New();
maskImageReader->SetFileName(maskFileName);
maskImageReader->UpdateOutputInformation();
maskFilter = MaskMuParserFilterType::New();
maskFilter->SetInput(maskImageReader->GetOutput());
std::string maskexpression = parseResult->GetParameterString("MaskExpression");
maskFilter->SetExpression(maskexpression);
maskFilter->UpdateOutputInformation();
if (parseResult->IsOptionPresent("IntermediateOutput"))
{
writer->SetInput(maskFilter->GetOutput());
writer->SetFileName("binaryMask.tif");
writer->Update();
}
connected->SetMaskImage(maskFilter->GetOutput());
}
else
if (parseResult->IsOptionPresent("InputImageMaskFileName"))
{
std::string maskFileName = parseResult->GetParameterString("InputImageMaskFileName");
maskReader = MaskReaderType::New();
maskReader->SetFileName(maskFileName);
maskReader->UpdateOutputInformation();
connected->SetMaskImage(maskReader->GetOutput());
}
// set up formula for connected component segmentation
std::string expression = parseResult->GetParameterString("Expression");
connected->GetFunctor().SetExpression(expression);
connected->Update();
if (parseResult->IsOptionPresent("IntermediateOutput"))
{
writer->SetInput(connected->GetOutput());
writer->SetFileName("connectedComponentLabelImage.tif");
writer->Update();
}
// relabel component
double minObjectSize;
if (parseResult->IsOptionPresent("MinSize"))
minObjectSize = parseResult->GetParameterDouble("MinSize");
else minObjectSize = 2;
// relabel connected component output
RelabelComponentFilterType::Pointer relabel = RelabelComponentFilterType::New();
relabel->SetInput(connected->GetOutput());
relabel->SetMinimumObjectSize(minObjectSize);
// debug output
if (parseResult->IsOptionPresent("IntermediateOutput"))
{
ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
colormapper->SetInput(relabel->GetOutput());
RGBWriterType::Pointer RGBwriter = RGBWriterType::New();
RGBwriter->SetInput(colormapper->GetOutput());
RGBwriter->SetFileName("RGBLabeledImage.tif");
RGBwriter->Update();
}
// step 3 transformation into labelmap and object characterization
//Attributes computation
// LabelImage to Label Map transformation
LabelImageToLabelMapFilterType::Pointer labelImageToLabelMap = LabelImageToLabelMapFilterType::New();
labelImageToLabelMap->SetInput(relabel->GetOutput());
labelImageToLabelMap->SetBackgroundValue(0);
// intermediate step : Fusion
// TBD
// shape attributes computation
ShapeLabelMapFilterType::Pointer shapeLabelMapFilter = ShapeLabelMapFilterType::New();
shapeLabelMapFilter->SetInput(labelImageToLabelMap->GetOutput());
shapeLabelMapFilter->SetReducedAttributeSet(false);
// band stat attributes computation
RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter = RadiometricLabelMapFilterType::New();
radiometricLabelMapFilter->SetInput(shapeLabelMapFilter->GetOutput());
radiometricLabelMapFilter->SetFeatureImage(reader->GetOutput());
radiometricLabelMapFilter->SetReducedAttributeSet(false);
radiometricLabelMapFilter->Update();
AttributesLabelMapType::Pointer AttributesLabelMap;
AttributesLabelMap = radiometricLabelMapFilter->GetOutput();
//AttributesLabelMap->SetAdjacencyMap(labelImageToLabelMap->GetOutput()->GetAdjacencyMap());
// step 4 OBIA Filtering using shape and radiometric object characteristics
std::string OBIAexpression = parseResult->GetParameterString("OBIAExpression");
LabelObjectOpeningFilterType::Pointer opening = LabelObjectOpeningFilterType::New();
opening->SetExpression(OBIAexpression);
opening->SetInput(radiometricLabelMapFilter->GetOutput());
opening->Update();
LabelMapToLabelImageFilterType::Pointer labelMapToLabelImage = LabelMapToLabelImageFilterType::New();
labelMapToLabelImage->SetInput(opening->GetOutput());
labelMapToLabelImage->Update();
if (parseResult->IsOptionPresent("IntermediateOutput"))
{
ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
colormapper->SetInput(labelMapToLabelImage->GetOutput());
RGBWriterType::Pointer RGBwriter = RGBWriterType::New();
RGBwriter->SetInput(colormapper->GetOutput());
RGBwriter->SetFileName("RGBOpeningOutput.tif");
RGBwriter->Update();
// removed object dbg output
LabelMapToLabelImageFilterType::Pointer labelMapToLabelImageRemoved = LabelMapToLabelImageFilterType::New();
labelMapToLabelImageRemoved->SetInput(opening->GetOutput(1));
labelMapToLabelImageRemoved->Update();
//ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
colormapper->SetInput(labelMapToLabelImageRemoved->GetOutput());
//RGBWriterType::Pointer RGBwriter = RGBWriterType::New();
RGBwriter->SetInput(colormapper->GetOutput());
RGBwriter->SetFileName("RGBOpeningRemovedObjects.tif");
RGBwriter->Update();
}
//step 5 : Vectorization
LabelMapToVectorDataFilterType::Pointer labelMapToVectorDataFilter = LabelMapToVectorDataFilterType::New();
labelMapToVectorDataFilter->SetInput(opening->GetOutput());
labelMapToVectorDataFilter->Update();
VectorDataPointerType vectorData = labelMapToVectorDataFilter->GetOutput();
// Instantiate the vdwriter
std::string vdoutFilename = parseResult->GetParameterString("OutputShapeFileName");
VectorDataFileWriterPointerType vdwriter = VectorDataFileWriterType::New();
vdwriter->SetInput(vectorData);
vdwriter->SetFileName(vdoutFilename);
vdwriter->Update();
// Instantiate the writer
std::string outFilename = parseResult->GetParameterString("OutputFileName");
writer->SetInput(labelMapToLabelImage->GetOutput());
writer->SetFileName(outFilename);
writer->Update();
return EXIT_SUCCESS;
}
}
<|endoftext|> |
<commit_before>#include "Histogram1DDataBlock.h"
#include "RasterDataBlock.h"
using namespace std;
using namespace UVFTables;
Histogram1DDataBlock::Histogram1DDataBlock() : DataBlock() {
ulBlockSemantics = BS_1D_HISTOGRAM;
strBlockID = "1D Histogram";
}
Histogram1DDataBlock::Histogram1DDataBlock(const Histogram1DDataBlock &other) :
DataBlock(other),
m_vHistData(other.m_vHistData)
{
}
Histogram1DDataBlock& Histogram1DDataBlock::operator=(const Histogram1DDataBlock& other) {
strBlockID = other.strBlockID;
ulBlockSemantics = other.ulBlockSemantics;
ulCompressionScheme = other.ulCompressionScheme;
ulOffsetToNextDataBlock = other.ulOffsetToNextDataBlock;
m_vHistData = other.m_vHistData;
return *this;
}
Histogram1DDataBlock::Histogram1DDataBlock(LargeRAWFile* pStreamFile, UINT64 iOffset, bool bIsBigEndian) {
GetHeaderFromFile(pStreamFile, iOffset, bIsBigEndian);
}
Histogram1DDataBlock::~Histogram1DDataBlock()
{
}
DataBlock* Histogram1DDataBlock::Clone() const {
return new Histogram1DDataBlock(*this);
}
UINT64 Histogram1DDataBlock::GetHeaderFromFile(LargeRAWFile* pStreamFile, UINT64 iOffset, bool bIsBigEndian) {
UINT64 iStart = iOffset + DataBlock::GetHeaderFromFile(pStreamFile, iOffset, bIsBigEndian);
pStreamFile->SeekPos(iStart);
UINT64 ulElementCount;
pStreamFile->ReadData(ulElementCount, bIsBigEndian);
m_vHistData.resize(size_t(ulElementCount));
pStreamFile->ReadRAW((unsigned char*)&m_vHistData[0], ulElementCount*sizeof(UINT64));
return pStreamFile->GetPos() - iOffset;
}
bool Histogram1DDataBlock::Compute(const RasterDataBlock* source) {
// TODO: right now we can only compute Histograms of scalar data this should be changed to a more general approach
if (source->ulElementDimension != 1 || source->ulElementDimensionSize.size() != 1) return false;
/// \todo right now compute Histogram assumes that at least the lowest LOD level consists only
// of a single brick, this brick is used for the hist.-computation
// this should be changed to a more general approach
vector<UINT64> vSmallestLOD = source->GetSmallestBrickIndex();
const vector<UINT64>& vBricks = source->GetBrickCount(vSmallestLOD);
for (size_t i = 0;i<vBricks.size();i++) if (vBricks[i] != 1) return false;
// create temp histogram
size_t iValueRange = size_t(1<<(source->ulElementBitSize[0][0]));
vector<UINT64> vTmpHist(iValueRange);
if (vTmpHist.size() != iValueRange) return false;
for (size_t i = 0;i<iValueRange;i++) vTmpHist[i] = 0;
// LargestSingleBrickLODBrickIndex is well defined as we tested above if we have a single brick LOD
std::vector<unsigned char> vcSourceData;
vector<UINT64> vLOD = source->LargestSingleBrickLODBrickIndex();
vector<UINT64> vOneAndOnly;
for (size_t i = 0;i<vBricks.size();i++) vOneAndOnly.push_back(0);
if (!source->GetData(vcSourceData, vLOD, vOneAndOnly)) return false;
vector<UINT64> vSize = source->LargestSingleBrickLODBrickSize();
UINT64 iDataSize = 1;
for (size_t i = 0;i<vSize.size();i++) iDataSize*=vSize[i];
/// @todo only 8 and 16 bit integer data are supported. this should be
/// changed to use a more general approach.
if (source->ulElementBitSize[0][0] == 8) {
for (UINT64 i = 0;i<iDataSize;i++) {
vTmpHist[vcSourceData[size_t(i)]]++;
}
} else {
if (source->ulElementBitSize[0][0] == 16) {
unsigned short *psSourceData = (unsigned short*)(&(vcSourceData.at(0)));
for (UINT64 i = 0;i<iDataSize;i++) {
vTmpHist[psSourceData[size_t(i)]]++;
}
} else {
return false;
}
}
// find maximum-index non zero entry
size_t iSize = 0;
for (size_t i = 0;i<iValueRange;i++) if (vTmpHist[i] != 0) iSize = i+1;
iValueRange = iSize;
// copy non zero elements in temp histogram to histogram
m_vHistData.resize(iValueRange);
if (m_vHistData.size() != iValueRange) return false;
for (size_t i = 0;i<iValueRange;i++) m_vHistData[i] = vTmpHist[i];
// set data block information
strBlockID = "1D Histogram for datablock " + source->strBlockID;
return true;
}
void Histogram1DDataBlock::CopyHeaderToFile(LargeRAWFile* pStreamFile, UINT64 iOffset, bool bIsBigEndian, bool bIsLastBlock) {
DataBlock::CopyHeaderToFile(pStreamFile, iOffset, bIsBigEndian, bIsLastBlock);
UINT64 ulElementCount = UINT64(m_vHistData.size());
pStreamFile->WriteData(ulElementCount, bIsBigEndian);
}
UINT64 Histogram1DDataBlock::CopyToFile(LargeRAWFile* pStreamFile, UINT64 iOffset, bool bIsBigEndian, bool bIsLastBlock) {
CopyHeaderToFile(pStreamFile, iOffset, bIsBigEndian, bIsLastBlock);
pStreamFile->WriteRAW((unsigned char*)&m_vHistData[0], m_vHistData.size()*sizeof(UINT64));
return pStreamFile->GetPos() - iOffset;
}
UINT64 Histogram1DDataBlock::GetOffsetToNextBlock() const {
return DataBlock::GetOffsetToNextBlock() + ComputeDataSize();
}
UINT64 Histogram1DDataBlock::ComputeDataSize() const {
return sizeof(UINT64) + // length of the vector
m_vHistData.size()*sizeof(UINT64); // the vector itself
}
<commit_msg>formatting.<commit_after>#include "Histogram1DDataBlock.h"
#include "RasterDataBlock.h"
using namespace std;
using namespace UVFTables;
Histogram1DDataBlock::Histogram1DDataBlock() : DataBlock() {
ulBlockSemantics = BS_1D_HISTOGRAM;
strBlockID = "1D Histogram";
}
Histogram1DDataBlock::Histogram1DDataBlock(const Histogram1DDataBlock &other) :
DataBlock(other),
m_vHistData(other.m_vHistData)
{
}
Histogram1DDataBlock& Histogram1DDataBlock::operator=(const Histogram1DDataBlock& other) {
strBlockID = other.strBlockID;
ulBlockSemantics = other.ulBlockSemantics;
ulCompressionScheme = other.ulCompressionScheme;
ulOffsetToNextDataBlock = other.ulOffsetToNextDataBlock;
m_vHistData = other.m_vHistData;
return *this;
}
Histogram1DDataBlock::Histogram1DDataBlock(LargeRAWFile* pStreamFile, UINT64 iOffset, bool bIsBigEndian) {
GetHeaderFromFile(pStreamFile, iOffset, bIsBigEndian);
}
Histogram1DDataBlock::~Histogram1DDataBlock()
{
}
DataBlock* Histogram1DDataBlock::Clone() const {
return new Histogram1DDataBlock(*this);
}
UINT64 Histogram1DDataBlock::GetHeaderFromFile(LargeRAWFile* pStreamFile, UINT64 iOffset, bool bIsBigEndian) {
UINT64 iStart = iOffset + DataBlock::GetHeaderFromFile(pStreamFile, iOffset, bIsBigEndian);
pStreamFile->SeekPos(iStart);
UINT64 ulElementCount;
pStreamFile->ReadData(ulElementCount, bIsBigEndian);
m_vHistData.resize(size_t(ulElementCount));
pStreamFile->ReadRAW((unsigned char*)&m_vHistData[0], ulElementCount*sizeof(UINT64));
return pStreamFile->GetPos() - iOffset;
}
bool Histogram1DDataBlock::Compute(const RasterDataBlock* source) {
// TODO: right now we can only compute Histograms of scalar data this
// should be changed to a more general approach
if (source->ulElementDimension != 1 ||
source->ulElementDimensionSize.size() != 1)
return false;
/// \todo right now compute Histogram assumes that at least the
// lowest LOD level consists only of a single brick, this brick is
// used for the hist.-computation this should be changed to a more
// general approach
vector<UINT64> vSmallestLOD = source->GetSmallestBrickIndex();
const vector<UINT64>& vBricks = source->GetBrickCount(vSmallestLOD);
for (size_t i = 0;i<vBricks.size();i++) if (vBricks[i] != 1) return false;
// create temp histogram
size_t iValueRange = size_t(1<<(source->ulElementBitSize[0][0]));
vector<UINT64> vTmpHist(iValueRange, 0);
if (vTmpHist.size() != iValueRange) return false;
// LargestSingleBrickLODBrickIndex is well defined as we tested above
// if we have a single brick LOD
std::vector<unsigned char> vcSourceData;
vector<UINT64> vLOD = source->LargestSingleBrickLODBrickIndex();
vector<UINT64> vOneAndOnly;
for (size_t i = 0;i<vBricks.size();i++) vOneAndOnly.push_back(0);
if (!source->GetData(vcSourceData, vLOD, vOneAndOnly)) return false;
vector<UINT64> vSize = source->LargestSingleBrickLODBrickSize();
UINT64 iDataSize = 1;
for (size_t i = 0;i<vSize.size();i++) iDataSize*=vSize[i];
/// @todo only 8 and 16 bit integer data are supported. this should be
/// changed to use a more general approach.
if (source->ulElementBitSize[0][0] == 8) {
for (UINT64 i = 0;i<iDataSize;i++) {
vTmpHist[vcSourceData[size_t(i)]]++;
}
} else {
if (source->ulElementBitSize[0][0] == 16) {
unsigned short *psSourceData = (unsigned short*)(&(vcSourceData.at(0)));
for (UINT64 i = 0;i<iDataSize;i++) {
vTmpHist[psSourceData[size_t(i)]]++;
}
} else {
return false;
}
}
// find maximum-index non zero entry
size_t iSize = 0;
for (size_t i = 0;i<iValueRange;i++) if (vTmpHist[i] != 0) iSize = i+1;
iValueRange = iSize;
// copy non zero elements in temp histogram to histogram
m_vHistData.resize(iValueRange);
if (m_vHistData.size() != iValueRange) return false;
for (size_t i = 0;i<iValueRange;i++) m_vHistData[i] = vTmpHist[i];
// set data block information
strBlockID = "1D Histogram for datablock " + source->strBlockID;
return true;
}
void Histogram1DDataBlock::CopyHeaderToFile(LargeRAWFile* pStreamFile, UINT64 iOffset, bool bIsBigEndian, bool bIsLastBlock) {
DataBlock::CopyHeaderToFile(pStreamFile, iOffset, bIsBigEndian, bIsLastBlock);
UINT64 ulElementCount = UINT64(m_vHistData.size());
pStreamFile->WriteData(ulElementCount, bIsBigEndian);
}
UINT64 Histogram1DDataBlock::CopyToFile(LargeRAWFile* pStreamFile, UINT64 iOffset, bool bIsBigEndian, bool bIsLastBlock) {
CopyHeaderToFile(pStreamFile, iOffset, bIsBigEndian, bIsLastBlock);
pStreamFile->WriteRAW((unsigned char*)&m_vHistData[0], m_vHistData.size()*sizeof(UINT64));
return pStreamFile->GetPos() - iOffset;
}
UINT64 Histogram1DDataBlock::GetOffsetToNextBlock() const {
return DataBlock::GetOffsetToNextBlock() + ComputeDataSize();
}
UINT64 Histogram1DDataBlock::ComputeDataSize() const {
return sizeof(UINT64) + // length of the vector
m_vHistData.size()*sizeof(UINT64); // the vector itself
}
<|endoftext|> |
<commit_before>#include <pwd.h>
#include <grp.h>
#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;
void printDashL(char* directoryName, vector<string> flags);
bool isDirectory(char* directoryName) {
struct stat directoryInCurrent;
if (-1 == (stat(directoryName, &directoryInCurrent))) {
return false;
}
if (directoryInCurrent.st_mode & S_IFDIR) {
return true;
}
else {
return false;
}
}
int ls(char* directoryName) {
if (!isDirectory(directoryName)) {
cout << directoryName << endl;
return 1;
}
char const *dirName = directoryName;
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
}
dirent *direntp;
while ((direntp = readdir(dirp))) {
if (direntp->d_name[0] != '.') {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
return 0;
}
void printDashL(char* directoryName, vector<string> flags) {
bool isA = false;
bool isL = false;
bool isR = false;
for (unsigned i = 0; i < flags.size(); ++i) {
for (unsigned k = 0; k < flags.at(i).size(); ++k) {
if (flags.at(i).at(k) == 'a')
isA = true; // there's an -a flag
else if (flags.at(i).at(k) == 'l')
isL = true; // there's an -l flag
else if (flags.at(i).at(k) == 'R')
isR = true; // there's an -R flag
}
}
struct stat current;
struct passwd *x;
struct group *y;
if (-1 == (stat(directoryName, ¤t))) {
perror("stat failed");
return;
}
if (current.st_mode & S_IFDIR)
cout << "d";
if (current.st_mode & S_IFLNK)
cout << "l";
if (!(current.st_mode & S_IFDIR) && !(current.st_mode & S_IFLNK))
cout << "-";
if (current.st_mode & S_IRUSR)
cout << "r";
else
cout << "-";
if (current.st_mode & S_IWUSR)
cout << "w";
else
cout << "-";
if (current.st_mode & S_IXUSR)
cout << "x";
else
cout << "-";
if (current.st_mode & S_IRGRP)
cout << "r";
else
cout << "-";
if (current.st_mode & S_IWGRP)
cout << "w";
else
cout << "-";
if (current.st_mode & S_IXGRP)
cout << "x";
else
cout << "-";
if (current.st_mode & S_IROTH)
cout << "r";
else
cout << "-";
if (current.st_mode & S_IWOTH)
cout << "w";
else
cout << "-";
if (current.st_mode & S_IXOTH)
cout << "x";
else
cout << "-";
cout << " ";
cout << current.st_nlink << " ";
if ((x = getpwuid(current.st_uid)) != NULL)
cout << x->pw_name << " ";
else {
cerr << "error: " << errno << endl;
exit(0);
}
if ((y = getgrgid(current.st_gid)) != NULL)
cout << y->gr_name << " ";
else {
cerr << "error: " << errno << endl;
exit(0);
}
cout << current.st_size << " ";
char buff[20];
struct tm * timeinfo;
timeinfo = localtime(&(current.st_mtime));
strftime(buff, 20, "%b %d %H:%M", timeinfo);
printf("%s",buff);
cout << " " << directoryName << endl;
}
int lsWithFlags(char* directoryName, vector<string> flags) {
if (!isDirectory(directoryName)) {
bool isA = false;
bool isL = false;
bool isR = false;
for (unsigned i = 0; i < flags.size(); ++i) {
for (unsigned k = 0; k < flags.at(i).size(); ++k) {
if (flags.at(i).at(k) == 'a')
isA = true; // there's an -a flag
else if (flags.at(i).at(k) == 'l')
isL = true; // there's an -l flag
else if (flags.at(i).at(k) == 'R')
isR = true; // there's an -R flag
}
}
if (isL) {
printDashL(directoryName, flags);
}
else {
cout << directoryName << endl;
}
return 1;
}
char const *dirName = directoryName;
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
return errno;
}
bool isA = false;
bool isL = false;
bool isR = false;
for (unsigned i = 0; i < flags.size(); ++i) {
for (unsigned k = 0; k < flags.at(i).size(); ++k) {
if (flags.at(i).at(k) == 'a')
isA = true; // there's an -a flag
else if (flags.at(i).at(k) == 'l')
isL = true; // there's an -l flag
else if (flags.at(i).at(k) == 'R')
isR = true; // there's an -R flag
}
}
dirent *direntp;
if (isR && isDirectory(directoryName)) {
vector<char*> dirsInCurdir;
int i = 0;
while ((direntp = readdir(dirp))) {
string temp = directoryName;
temp.append("/");
temp.append(direntp->d_name);
char *x;
x = new char[temp.size() + 1];
strcpy(x, temp.c_str());
dirsInCurdir.push_back(x);
++i;
}
for (int j = 0; j < i; ++i) {
cout << *dirsInCurdir[j] << ":\n";
return lsWithFlags(dirsInCurdir[j], flags);
cout << endl;
for (int j = 0; j < i; ++j)
delete [] dirsInCurdir[j];
}
if (!isL && !isA)
return ls(directoryName);
if (isL) { //run -l flag
struct stat current;
struct passwd *x;
struct group *y;
while ((direntp = readdir(dirp))) {
string temp = directoryName;
temp.append("/");
temp.append(direntp->d_name);
//cout << "direntp: " << direntp->d_name << endl;
char* curdir = new char[temp.size() + 1];
strcpy(curdir, temp.c_str());
//cout << curdir << endl;
if (-1 == (stat(curdir, ¤t))) {
perror("stat failed");
return -1;
}
if (direntp->d_name[0] == '.' && !isA) { // if there's no -a flag, don't print files
// starting with .
continue;
}
else {
if (current.st_mode & S_IFDIR)
cout << "d";
if (current.st_mode & S_IFLNK)
cout << "l";
if (!(current.st_mode & S_IFDIR) && !(current.st_mode & S_IFLNK))
cout << "-";
if (current.st_mode & S_IRUSR)
cout << "r";
else
cout << "-";
if (current.st_mode & S_IWUSR)
cout << "w";
else
cout << "-";
if (current.st_mode & S_IXUSR)
cout << "x";
else
cout << "-";
if (current.st_mode & S_IRGRP)
cout << "r";
else
cout << "-";
if (current.st_mode & S_IWGRP)
cout << "w";
else
cout << "-";
if (current.st_mode & S_IXGRP)
cout << "x";
else
cout << "-";
if (current.st_mode & S_IROTH)
cout << "r";
else
cout << "-";
if (current.st_mode & S_IWOTH)
cout << "w";
else
cout << "-";
if (current.st_mode & S_IXOTH)
cout << "x";
else
cout << "-";
cout << " ";
cout << current.st_nlink << " ";
if ((x = getpwuid(current.st_uid)) != NULL)
cout << x->pw_name << " ";
else {
cerr << "error: " << errno << endl;
exit(0);
}
if ((y = getgrgid(current.st_gid)) != NULL)
cout << y->gr_name << " ";
else {
cerr << "error: " << errno << endl;
exit(0);
}
cout << current.st_size << " ";
char buff[20];
struct tm * timeinfo;
timeinfo = localtime(&(current.st_mtime));
strftime(buff, 20, "%b %d %H:%M", timeinfo);
printf("%s",buff);
cout << " " << direntp->d_name;
}
cout << endl;
delete [] curdir;
}
closedir(dirp);
}
else if (isA) {
while ((direntp = readdir(dirp))) {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
if (-1 == (closedir(dirp))) {
perror("closedir failed");
}
cout << endl;
}
return 0;
}
int main(int argc, char* argv[]) {
if (argc == 1) {
if (errno == ls(".")) {
return errno;
}
}
else {
vector<string> directories;
vector<string> flags;
string toInsert = "./";
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == '-') {
flags.push_back(argv[i]);
} else {
directories.push_back(argv[i]);
}
}
for (unsigned i = 0; i < directories.size(); ++i) {
directories.at(i).insert(0, toInsert);
}
if (flags.size() == 0) {
for (unsigned i = 0; i < directories.size(); ++i) {
char* directoryName = new char[directories.at(i).size() + 1];
strcpy(directoryName, directories.at(i).c_str());
ls(directoryName);
delete [] directoryName;
}
}
else if (directories.size() == 0) {
lsWithFlags(".", flags);
}
else {
//cout << "directories: ";
//for (unsigned i = 0; i < directories.size(); ++i)
//cout << directories.at(i) << " ";
//cout << endl;
if (directories.size() == 1) {
char* directoryName = new char[directories.at(0).size() + 1];
strcpy(directoryName, directories.at(0).c_str());
lsWithFlags(directoryName, flags);
delete [] directoryName;
}
else {
for (unsigned int i = 0; i < directories.size(); ++i) {
//cout << 145 << endl;
char* directoryName = new char[directories.at(i).size() + 1];
strcpy(directoryName, directories.at(i).c_str());
cout << directoryName << ":" << endl;
lsWithFlags(directoryName, flags);
delete [] directoryName;
cout << endl;
}
}
}
}
}
<commit_msg>added -l protection functionality<commit_after>#include <pwd.h>
#include <grp.h>
#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;
void printDashL(char* directoryName, vector<string> flags);
bool isDirectory(char* directoryName) {
struct stat directoryInCurrent;
if (-1 == (stat(directoryName, &directoryInCurrent))) {
return false;
}
if (directoryInCurrent.st_mode & S_IFDIR) {
return true;
}
else {
return false;
}
}
int ls(char* directoryName) {
if (!isDirectory(directoryName)) {
cout << directoryName << endl;
return 1;
}
char const *dirName = directoryName;
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
}
dirent *direntp;
while ((direntp = readdir(dirp))) {
if (direntp->d_name[0] != '.') {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
return 0;
}
void printDashL(char* directoryName, vector<string> flags) {
bool isA = false;
bool isL = false;
bool isR = false;
for (unsigned i = 0; i < flags.size(); ++i) {
for (unsigned k = 0; k < flags.at(i).size(); ++k) {
if (flags.at(i).at(k) == 'a')
isA = true; // there's an -a flag
else if (flags.at(i).at(k) == 'l')
isL = true; // there's an -l flag
else if (flags.at(i).at(k) == 'R')
isR = true; // there's an -R flag
}
}
struct stat current;
struct passwd *x;
struct group *y;
if (-1 == (stat(directoryName, ¤t))) {
perror("stat failed");
return;
}
if (current.st_mode & S_IFDIR)
cout << "d";
if (current.st_mode & S_IFLNK)
cout << "l";
if (!(current.st_mode & S_IFDIR) && !(current.st_mode & S_IFLNK))
cout << "-";
if (current.st_mode & S_IRUSR)
cout << "r";
else
cout << "-";
if (current.st_mode & S_IWUSR)
cout << "w";
else
cout << "-";
if (current.st_mode & S_IXUSR)
cout << "x";
else
cout << "-";
if (current.st_mode & S_IRGRP)
cout << "r";
else
cout << "-";
if (current.st_mode & S_IWGRP)
cout << "w";
else
cout << "-";
if (current.st_mode & S_IXGRP)
cout << "x";
else
cout << "-";
if (current.st_mode & S_IROTH)
cout << "r";
else
cout << "-";
if (current.st_mode & S_IWOTH)
cout << "w";
else
cout << "-";
if (current.st_mode & S_IXOTH)
cout << "x";
else
cout << "-";
cout << " ";
cout << current.st_nlink << " ";
if ((x = getpwuid(current.st_uid)) != NULL)
cout << x->pw_name << " ";
else {
cerr << "error: " << errno << endl;
exit(0);
}
if ((y = getgrgid(current.st_gid)) != NULL)
cout << y->gr_name << " ";
else {
cerr << "error: " << errno << endl;
exit(0);
}
cout << current.st_size << " ";
char buff[20];
struct tm * timeinfo;
timeinfo = localtime(&(current.st_mtime));
strftime(buff, 20, "%b %d %H:%M", timeinfo);
printf("%s",buff);
cout << " " << directoryName << endl;
}
int lsWithFlags(char* directoryName, vector<string> flags) {
if (!isDirectory(directoryName)) {
bool isA = false;
bool isL = false;
bool isR = false;
for (unsigned i = 0; i < flags.size(); ++i) {
for (unsigned k = 0; k < flags.at(i).size(); ++k) {
if (flags.at(i).at(k) == 'a')
isA = true; // there's an -a flag
else if (flags.at(i).at(k) == 'l')
isL = true; // there's an -l flag
else if (flags.at(i).at(k) == 'R')
isR = true; // there's an -R flag
}
}
if (isL) {
printDashL(directoryName, flags);
}
else {
cout << directoryName << endl;
}
return 1;
}
char const *dirName = directoryName;
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
return errno;
}
bool isA = false;
bool isL = false;
bool isR = false;
for (unsigned i = 0; i < flags.size(); ++i) {
for (unsigned k = 0; k < flags.at(i).size(); ++k) {
if (flags.at(i).at(k) == 'a')
isA = true; // there's an -a flag
else if (flags.at(i).at(k) == 'l')
isL = true; // there's an -l flag
else if (flags.at(i).at(k) == 'R')
isR = true; // there's an -R flag
}
}
dirent *direntp;
if (isR && isDirectory(directoryName)) {
vector<char*> dirsInCurdir;
int i = 0;
while ((direntp = readdir(dirp))) {
string temp = directoryName;
temp.append("/");
temp.append(direntp->d_name);
char *x;
x = new char[temp.size() + 1];
strcpy(x, temp.c_str());
dirsInCurdir.push_back(x);
++i;
}
for (int j = 0; j < i; ++i) {
cout << *dirsInCurdir[j] << ":\n";
return lsWithFlags(dirsInCurdir[j], flags);
cout << endl;
}
for (int j = 0; j < i; ++j)
delete [] dirsInCurdir[j];
}
if (!isL && !isA)
return ls(directoryName);
if (isL) { //run -l flag
struct stat current;
struct passwd *x;
struct group *y;
while ((direntp = readdir(dirp))) {
string temp = directoryName;
temp.append("/");
temp.append(direntp->d_name);
//cout << "direntp: " << direntp->d_name << endl;
char* curdir = new char[temp.size() + 1];
strcpy(curdir, temp.c_str());
//cout << curdir << endl;
if (-1 == (stat(curdir, ¤t))) {
perror("stat failed");
return -1;
}
if (direntp->d_name[0] == '.' && !isA) { // if there's no -a flag, don't print files
// starting with .
continue;
}
else {
if (current.st_mode & S_IFDIR)
cout << "d";
if (current.st_mode & S_IFLNK)
cout << "l";
if (!(current.st_mode & S_IFDIR) && !(current.st_mode & S_IFLNK))
cout << "-";
if (current.st_mode & S_IRUSR)
cout << "r";
else
cout << "-";
if (current.st_mode & S_IWUSR)
cout << "w";
else
cout << "-";
if (current.st_mode & S_IXUSR)
cout << "x";
else
cout << "-";
if (current.st_mode & S_IRGRP)
cout << "r";
else
cout << "-";
if (current.st_mode & S_IWGRP)
cout << "w";
else
cout << "-";
if (current.st_mode & S_IXGRP)
cout << "x";
else
cout << "-";
if (current.st_mode & S_IROTH)
cout << "r";
else
cout << "-";
if (current.st_mode & S_IWOTH)
cout << "w";
else
cout << "-";
if (current.st_mode & S_IXOTH)
cout << "x";
else
cout << "-";
cout << " ";
cout << current.st_nlink << " ";
if ((x = getpwuid(current.st_uid)) != NULL)
cout << x->pw_name << " ";
else {
cerr << "error: " << errno << endl;
exit(0);
}
if ((y = getgrgid(current.st_gid)) != NULL)
cout << y->gr_name << " ";
else {
cerr << "error: " << errno << endl;
exit(0);
}
cout << current.st_size << " ";
char buff[20];
struct tm * timeinfo;
timeinfo = localtime(&(current.st_mtime));
strftime(buff, 20, "%b %d %H:%M", timeinfo);
printf("%s",buff);
cout << " " << direntp->d_name;
}
cout << endl;
delete [] curdir;
}
closedir(dirp);
}
else if (isA) {
while ((direntp = readdir(dirp))) {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
if (-1 == (closedir(dirp))) {
perror("closedir failed");
}
cout << endl;
}
return 0;
}
int main(int argc, char* argv[]) {
if (argc == 1) {
if (errno == ls(".")) {
return errno;
}
}
else {
vector<string> directories;
vector<string> flags;
string toInsert = "./";
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == '-') {
flags.push_back(argv[i]);
} else {
directories.push_back(argv[i]);
}
}
for (unsigned i = 0; i < directories.size(); ++i) {
directories.at(i).insert(0, toInsert);
}
if (flags.size() == 0) {
for (unsigned i = 0; i < directories.size(); ++i) {
char* directoryName = new char[directories.at(i).size() + 1];
strcpy(directoryName, directories.at(i).c_str());
ls(directoryName);
delete [] directoryName;
}
}
else if (directories.size() == 0) {
lsWithFlags(".", flags);
}
else {
//cout << "directories: ";
//for (unsigned i = 0; i < directories.size(); ++i)
//cout << directories.at(i) << " ";
//cout << endl;
if (directories.size() == 1) {
char* directoryName = new char[directories.at(0).size() + 1];
strcpy(directoryName, directories.at(0).c_str());
lsWithFlags(directoryName, flags);
delete [] directoryName;
}
else {
for (unsigned int i = 0; i < directories.size(); ++i) {
//cout << 145 << endl;
char* directoryName = new char[directories.at(i).size() + 1];
strcpy(directoryName, directories.at(i).c_str());
cout << directoryName << ":" << endl;
lsWithFlags(directoryName, flags);
delete [] directoryName;
cout << endl;
}
}
}
}
}
<|endoftext|> |
<commit_before>#include <UnitTest/stdafx.h>
#include <UnitTest/UnitTest.h>
#include <core/addin/addin.h>
#include <core/addin/mfcmapi.h>
namespace addin
{
// imports for testing
int _cdecl compareTypes(_In_ const void* a1, _In_ const void* a2) noexcept;
int _cdecl compareTags(_In_ const void* a1, _In_ const void* a2) noexcept;
int _cdecl compareNameID(_In_ const void* a1, _In_ const void* a2) noexcept;
int _cdecl compareSmartViewParser(_In_ const void* a1, _In_ const void* a2) noexcept;
void SortFlagArray(_In_count_(ulFlags) LPFLAG_ARRAY_ENTRY lpFlags, _In_ size_t ulFlags) noexcept;
void AppendFlagIfNotDupe(std::vector<FLAG_ARRAY_ENTRY>& target, FLAG_ARRAY_ENTRY source);
void MergeFlagArrays(std::vector<FLAG_ARRAY_ENTRY>& In1, _In_count_(cIn2) LPFLAG_ARRAY_ENTRY In2, _In_ size_t cIn2);
} // namespace addin
namespace addintest
{
int _cdecl testCompareTypes(_In_ const NAME_ARRAY_ENTRY& a1, _In_ const NAME_ARRAY_ENTRY& a2) noexcept
{
return addin::compareTypes(reinterpret_cast<LPCVOID>(&a1), reinterpret_cast<LPCVOID>(&a2));
}
int _cdecl testCompareTags(_In_ const NAME_ARRAY_ENTRY_V2& a1, _In_ const NAME_ARRAY_ENTRY_V2& a2) noexcept
{
return addin::compareTags(reinterpret_cast<LPCVOID>(&a1), reinterpret_cast<LPCVOID>(&a2));
}
int _cdecl testCompareNameID(_In_ const NAMEID_ARRAY_ENTRY& a1, _In_ const NAMEID_ARRAY_ENTRY& a2) noexcept
{
return addin::compareNameID(reinterpret_cast<LPCVOID>(&a1), reinterpret_cast<LPCVOID>(&a2));
}
int _cdecl testCompareSmartViewParser(
_In_ const SMARTVIEW_PARSER_ARRAY_ENTRY& a1,
_In_ const SMARTVIEW_PARSER_ARRAY_ENTRY& a2) noexcept
{
return addin::compareSmartViewParser(reinterpret_cast<LPCVOID>(&a1), reinterpret_cast<LPCVOID>(&a2));
}
TEST_CLASS(addinTest)
{
public:
// Without this, clang gets weird
static const bool dummy_var = true;
TEST_CLASS_INITIALIZE(initialize) { unittest::init(); }
TEST_METHOD(Test_compareTypes)
{
Assert::AreEqual(0, testCompareTypes({1, L"one"}, {1, L"one"}));
Assert::AreEqual(-1, testCompareTypes({1, L"one"}, {2, L"two"}));
Assert::AreEqual(1, testCompareTypes({2, L"two"}, {1, L"one"}));
Assert::AreEqual(-1, testCompareTypes({1, L"a"}, {1, L"b"}));
Assert::AreEqual(1, testCompareTypes({1, L"b"}, {1, L"a"}));
// Same name gets no special treatment
Assert::AreEqual(-1, testCompareTypes({1, L"one"}, {2, L"one"}));
Assert::AreEqual(1, testCompareTypes({2, L"one"}, {1, L"one"}));
}
TEST_METHOD(Test_compareTags)
{
Assert::AreEqual(0, testCompareTags({1, 0, L"one"}, {1, 0, L"one"}));
Assert::AreEqual(-1, testCompareTags({1, 0, L"one"}, {2, 0, L"two"}));
Assert::AreEqual(1, testCompareTags({2, 0, L"two"}, {1, 0, L"one"}));
Assert::AreEqual(-1, testCompareTags({1, 0, L"a"}, {1, 0, L"b"}));
Assert::AreEqual(-1, testCompareTags({1, 0, L"a"}, {1, 1, L"b"}));
// Sort order field doesn't actually affect this particular sort
Assert::AreEqual(-1, testCompareTags({1, 1, L"a"}, {1, 0, L"b"}));
Assert::AreEqual(1, testCompareTags({1, 0, L"b"}, {1, 0, L"a"}));
// Same name compares equal
Assert::AreEqual(0, testCompareTags({1, 0, L"one"}, {2, 0, L"one"}));
}
TEST_METHOD(Test_compareNameID)
{
Assert::AreEqual(
0,
testCompareNameID(
{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"},
{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"}));
Assert::AreEqual(
-1,
testCompareNameID(
{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"},
{2, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"}));
Assert::AreEqual(
1,
testCompareNameID(
{2, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"},
{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"}));
Assert::AreEqual(
-1,
testCompareNameID(
{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"},
{1, &guid::PSETID_Note, L"a", PT_SYSTIME, L"aa"}));
Assert::AreEqual(
-1,
testCompareNameID(
{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"},
{1, &guid::PSETID_Meeting, L"b", PT_SYSTIME, L"bb"}));
Assert::AreEqual(
1,
testCompareNameID(
{1, &guid::PSETID_Meeting, L"b", PT_SYSTIME, L"bb"},
{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"}));
}
TEST_METHOD(Test_CompareSmartViewParser)
{
Assert::AreEqual(
0, testCompareSmartViewParser({1, parserType::REPORTTAG, false}, {1, parserType::REPORTTAG, false}));
Assert::AreEqual(
-1, testCompareSmartViewParser({1, parserType::REPORTTAG, false}, {2, parserType::REPORTTAG, false}));
Assert::AreEqual(
1, testCompareSmartViewParser({2, parserType::REPORTTAG, false}, {1, parserType::REPORTTAG, false}));
Assert::AreEqual(
-1, testCompareSmartViewParser({1, parserType::ENTRYID, false}, {1, parserType::REPORTTAG, false}));
Assert::AreEqual(
1, testCompareSmartViewParser({1, parserType::REPORTTAG, false}, {1, parserType::ENTRYID, false}));
Assert::AreEqual(
-1, testCompareSmartViewParser({1, parserType::REPORTTAG, false}, {1, parserType::REPORTTAG, true}));
Assert::AreEqual(
1, testCompareSmartViewParser({1, parserType::REPORTTAG, true}, {1, parserType::REPORTTAG, false}));
}
void testFA(std::wstring testName, const FLAG_ARRAY_ENTRY& fa1, const FLAG_ARRAY_ENTRY& fa2)
{
Assert::AreEqual(fa1.ulFlagName, fa2.ulFlagName, (testName + L"-ulFlagName").c_str());
Assert::AreEqual(fa1.lFlagValue, fa2.lFlagValue, (testName + L"-lFlagValue").c_str());
Assert::AreEqual(fa1.ulFlagType, fa2.ulFlagType, (testName + L"-ulFlagType").c_str());
Assert::AreEqual(fa1.lpszName, fa2.lpszName, (testName + L"-lpszName").c_str());
}
TEST_METHOD(Test_FlagArray)
{
FLAG_ARRAY_ENTRY flagArray[] = {
{2, 1, flagVALUE, L"b one"},
{1, 2, flagVALUE, L"two"},
{2, 3, flagVALUE, L"a three"},
{1, 1, flagVALUE, L"one"},
};
// Do a stable sort on ulFlagName (first member)
addin::SortFlagArray(flagArray, _countof(flagArray));
testFA(L"0", flagArray[0], {1, 2, flagVALUE, L"two"});
testFA(L"1", flagArray[1], {1, 1, flagVALUE, L"one"});
testFA(L"2", flagArray[2], {2, 1, flagVALUE, L"b one"});
testFA(L"3", flagArray[3], {2, 3, flagVALUE, L"a three"});
auto flagV = std::vector<FLAG_ARRAY_ENTRY>{};
addin::AppendFlagIfNotDupe(flagV, {1, 3, flagVALUE, L"three"});
testFA(L"add 1", flagV[0], {1, 3, flagVALUE, L"three"});
addin::AppendFlagIfNotDupe(flagV, {1, 4, flagVALUE, L"one"});
testFA(L"add 2", flagV[1], {1, 4, flagVALUE, L"one"});
addin::AppendFlagIfNotDupe(flagV, {1, 4, flagVALUE, L"one"});
Assert::AreEqual(size_t{2}, flagV.size(), L"no dupe");
addin::AppendFlagIfNotDupe(flagV, {2, 2, flagVALUE, L"c two"});
testFA(L"add 3", flagV[2], {2, 2, flagVALUE, L"c two"});
addin::MergeFlagArrays(flagV, flagArray, _countof(flagArray));
Assert::AreEqual(size_t{7}, flagV.size(), L"merge size");
testFA(L"m0", flagV[0], {1, 3, flagVALUE, L"three"});
testFA(L"m1", flagV[1], {1, 4, flagVALUE, L"one"});
testFA(L"m2", flagV[2], {1, 2, flagVALUE, L"two"});
testFA(L"m3", flagV[3], {1, 1, flagVALUE, L"one"});
testFA(L"m4", flagV[4], {2, 2, flagVALUE, L"c two"});
testFA(L"m5", flagV[5], {2, 1, flagVALUE, L"b one"});
testFA(L"m6", flagV[6], {2, 3, flagVALUE, L"a three"});
auto flagV2 = std::vector<FLAG_ARRAY_ENTRY>{};
addin::AppendFlagIfNotDupe(flagV2, {4, 3, flagVALUE, L"three"});
testFA(L"f2 add 1", flagV2[0], {4, 3, flagVALUE, L"three"});
addin::MergeFlagArrays(flagV2, nullptr, 0);
Assert::AreEqual(size_t{1}, flagV2.size(), L"merge null");
addin::AppendFlagIfNotDupe(flagV2, {4, 4, flagVALUE, L"four"});
Assert::AreEqual(size_t{2}, flagV2.size(), L"merge null");
testFA(L"f2 add 2", flagV2[1], {4, 4, flagVALUE, L"four"});
FLAG_ARRAY_ENTRY flagArray2[] = {{3, 1, flagVALUE, L"four one"}};
addin::MergeFlagArrays(flagV2, flagArray2, _countof(flagArray2));
Assert::AreEqual(size_t{3}, flagV2.size(), L"merge null");
testFA(L"f2 merge", flagV2[0], {3, 1, flagVALUE, L"four one"});
}
};
} // namespace addintest<commit_msg>add another test<commit_after>#include <UnitTest/stdafx.h>
#include <UnitTest/UnitTest.h>
#include <core/addin/addin.h>
#include <core/addin/mfcmapi.h>
namespace addin
{
// imports for testing
int _cdecl compareTypes(_In_ const void* a1, _In_ const void* a2) noexcept;
int _cdecl compareTags(_In_ const void* a1, _In_ const void* a2) noexcept;
int _cdecl compareNameID(_In_ const void* a1, _In_ const void* a2) noexcept;
int _cdecl compareSmartViewParser(_In_ const void* a1, _In_ const void* a2) noexcept;
std::wstring AddInStructTypeToString(parserType parser);
void SortFlagArray(_In_count_(ulFlags) LPFLAG_ARRAY_ENTRY lpFlags, _In_ size_t ulFlags) noexcept;
void AppendFlagIfNotDupe(std::vector<FLAG_ARRAY_ENTRY>& target, FLAG_ARRAY_ENTRY source);
void MergeFlagArrays(std::vector<FLAG_ARRAY_ENTRY>& In1, _In_count_(cIn2) LPFLAG_ARRAY_ENTRY In2, _In_ size_t cIn2);
} // namespace addin
namespace addintest
{
int _cdecl testCompareTypes(_In_ const NAME_ARRAY_ENTRY& a1, _In_ const NAME_ARRAY_ENTRY& a2) noexcept
{
return addin::compareTypes(reinterpret_cast<LPCVOID>(&a1), reinterpret_cast<LPCVOID>(&a2));
}
int _cdecl testCompareTags(_In_ const NAME_ARRAY_ENTRY_V2& a1, _In_ const NAME_ARRAY_ENTRY_V2& a2) noexcept
{
return addin::compareTags(reinterpret_cast<LPCVOID>(&a1), reinterpret_cast<LPCVOID>(&a2));
}
int _cdecl testCompareNameID(_In_ const NAMEID_ARRAY_ENTRY& a1, _In_ const NAMEID_ARRAY_ENTRY& a2) noexcept
{
return addin::compareNameID(reinterpret_cast<LPCVOID>(&a1), reinterpret_cast<LPCVOID>(&a2));
}
int _cdecl testCompareSmartViewParser(
_In_ const SMARTVIEW_PARSER_ARRAY_ENTRY& a1,
_In_ const SMARTVIEW_PARSER_ARRAY_ENTRY& a2) noexcept
{
return addin::compareSmartViewParser(reinterpret_cast<LPCVOID>(&a1), reinterpret_cast<LPCVOID>(&a2));
}
TEST_CLASS(addinTest)
{
public:
// Without this, clang gets weird
static const bool dummy_var = true;
TEST_CLASS_INITIALIZE(initialize) { unittest::init(); }
TEST_METHOD(Test_compareTypes)
{
Assert::AreEqual(0, testCompareTypes({1, L"one"}, {1, L"one"}));
Assert::AreEqual(-1, testCompareTypes({1, L"one"}, {2, L"two"}));
Assert::AreEqual(1, testCompareTypes({2, L"two"}, {1, L"one"}));
Assert::AreEqual(-1, testCompareTypes({1, L"a"}, {1, L"b"}));
Assert::AreEqual(1, testCompareTypes({1, L"b"}, {1, L"a"}));
// Same name gets no special treatment
Assert::AreEqual(-1, testCompareTypes({1, L"one"}, {2, L"one"}));
Assert::AreEqual(1, testCompareTypes({2, L"one"}, {1, L"one"}));
}
TEST_METHOD(Test_compareTags)
{
Assert::AreEqual(0, testCompareTags({1, 0, L"one"}, {1, 0, L"one"}));
Assert::AreEqual(-1, testCompareTags({1, 0, L"one"}, {2, 0, L"two"}));
Assert::AreEqual(1, testCompareTags({2, 0, L"two"}, {1, 0, L"one"}));
Assert::AreEqual(-1, testCompareTags({1, 0, L"a"}, {1, 0, L"b"}));
Assert::AreEqual(-1, testCompareTags({1, 0, L"a"}, {1, 1, L"b"}));
// Sort order field doesn't actually affect this particular sort
Assert::AreEqual(-1, testCompareTags({1, 1, L"a"}, {1, 0, L"b"}));
Assert::AreEqual(1, testCompareTags({1, 0, L"b"}, {1, 0, L"a"}));
// Same name compares equal
Assert::AreEqual(0, testCompareTags({1, 0, L"one"}, {2, 0, L"one"}));
}
TEST_METHOD(Test_compareNameID)
{
Assert::AreEqual(
0,
testCompareNameID(
{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"},
{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"}));
Assert::AreEqual(
-1,
testCompareNameID(
{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"},
{2, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"}));
Assert::AreEqual(
1,
testCompareNameID(
{2, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"},
{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"}));
Assert::AreEqual(
-1,
testCompareNameID(
{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"},
{1, &guid::PSETID_Note, L"a", PT_SYSTIME, L"aa"}));
Assert::AreEqual(
-1,
testCompareNameID(
{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"},
{1, &guid::PSETID_Meeting, L"b", PT_SYSTIME, L"bb"}));
Assert::AreEqual(
1,
testCompareNameID(
{1, &guid::PSETID_Meeting, L"b", PT_SYSTIME, L"bb"},
{1, &guid::PSETID_Meeting, L"a", PT_SYSTIME, L"aa"}));
}
TEST_METHOD(Test_CompareSmartViewParser)
{
Assert::AreEqual(
0, testCompareSmartViewParser({1, parserType::REPORTTAG, false}, {1, parserType::REPORTTAG, false}));
Assert::AreEqual(
-1, testCompareSmartViewParser({1, parserType::REPORTTAG, false}, {2, parserType::REPORTTAG, false}));
Assert::AreEqual(
1, testCompareSmartViewParser({2, parserType::REPORTTAG, false}, {1, parserType::REPORTTAG, false}));
Assert::AreEqual(
-1, testCompareSmartViewParser({1, parserType::ENTRYID, false}, {1, parserType::REPORTTAG, false}));
Assert::AreEqual(
1, testCompareSmartViewParser({1, parserType::REPORTTAG, false}, {1, parserType::ENTRYID, false}));
Assert::AreEqual(
-1, testCompareSmartViewParser({1, parserType::REPORTTAG, false}, {1, parserType::REPORTTAG, true}));
Assert::AreEqual(
1, testCompareSmartViewParser({1, parserType::REPORTTAG, true}, {1, parserType::REPORTTAG, false}));
}
//AddInStructTypeToString
TEST_METHOD(Test_AddInStructTypeToString)
{
Assert::AreEqual(
L"Choose Smart View Parser",
addin::AddInStructTypeToString(parserType::NOPARSING).c_str(),
L"NOPARSING");
Assert::AreEqual(L"", addin::AddInStructTypeToString(parserType{0xfff}).c_str(), L"unknown");
}
void testFA(std::wstring testName, const FLAG_ARRAY_ENTRY& fa1, const FLAG_ARRAY_ENTRY& fa2)
{
Assert::AreEqual(fa1.ulFlagName, fa2.ulFlagName, (testName + L"-ulFlagName").c_str());
Assert::AreEqual(fa1.lFlagValue, fa2.lFlagValue, (testName + L"-lFlagValue").c_str());
Assert::AreEqual(fa1.ulFlagType, fa2.ulFlagType, (testName + L"-ulFlagType").c_str());
Assert::AreEqual(fa1.lpszName, fa2.lpszName, (testName + L"-lpszName").c_str());
}
TEST_METHOD(Test_FlagArray)
{
FLAG_ARRAY_ENTRY flagArray[] = {
{2, 1, flagVALUE, L"b one"},
{1, 2, flagVALUE, L"two"},
{2, 3, flagVALUE, L"a three"},
{1, 1, flagVALUE, L"one"},
};
// Do a stable sort on ulFlagName (first member)
addin::SortFlagArray(flagArray, _countof(flagArray));
testFA(L"0", flagArray[0], {1, 2, flagVALUE, L"two"});
testFA(L"1", flagArray[1], {1, 1, flagVALUE, L"one"});
testFA(L"2", flagArray[2], {2, 1, flagVALUE, L"b one"});
testFA(L"3", flagArray[3], {2, 3, flagVALUE, L"a three"});
auto flagV = std::vector<FLAG_ARRAY_ENTRY>{};
addin::AppendFlagIfNotDupe(flagV, {1, 3, flagVALUE, L"three"});
testFA(L"add 1", flagV[0], {1, 3, flagVALUE, L"three"});
addin::AppendFlagIfNotDupe(flagV, {1, 4, flagVALUE, L"one"});
testFA(L"add 2", flagV[1], {1, 4, flagVALUE, L"one"});
addin::AppendFlagIfNotDupe(flagV, {1, 4, flagVALUE, L"one"});
Assert::AreEqual(size_t{2}, flagV.size(), L"no dupe");
addin::AppendFlagIfNotDupe(flagV, {2, 2, flagVALUE, L"c two"});
testFA(L"add 3", flagV[2], {2, 2, flagVALUE, L"c two"});
addin::MergeFlagArrays(flagV, flagArray, _countof(flagArray));
Assert::AreEqual(size_t{7}, flagV.size(), L"merge size");
testFA(L"m0", flagV[0], {1, 3, flagVALUE, L"three"});
testFA(L"m1", flagV[1], {1, 4, flagVALUE, L"one"});
testFA(L"m2", flagV[2], {1, 2, flagVALUE, L"two"});
testFA(L"m3", flagV[3], {1, 1, flagVALUE, L"one"});
testFA(L"m4", flagV[4], {2, 2, flagVALUE, L"c two"});
testFA(L"m5", flagV[5], {2, 1, flagVALUE, L"b one"});
testFA(L"m6", flagV[6], {2, 3, flagVALUE, L"a three"});
auto flagV2 = std::vector<FLAG_ARRAY_ENTRY>{};
addin::AppendFlagIfNotDupe(flagV2, {4, 3, flagVALUE, L"three"});
testFA(L"f2 add 1", flagV2[0], {4, 3, flagVALUE, L"three"});
addin::MergeFlagArrays(flagV2, nullptr, 0);
Assert::AreEqual(size_t{1}, flagV2.size(), L"merge null");
addin::AppendFlagIfNotDupe(flagV2, {4, 4, flagVALUE, L"four"});
Assert::AreEqual(size_t{2}, flagV2.size(), L"merge null");
testFA(L"f2 add 2", flagV2[1], {4, 4, flagVALUE, L"four"});
FLAG_ARRAY_ENTRY flagArray2[] = {{3, 1, flagVALUE, L"four one"}};
addin::MergeFlagArrays(flagV2, flagArray2, _countof(flagArray2));
Assert::AreEqual(size_t{3}, flagV2.size(), L"merge null");
testFA(L"f2 merge", flagV2[0], {3, 1, flagVALUE, L"four one"});
}
};
} // namespace addintest<|endoftext|> |
<commit_before>/*
* SoapyRedPitaya: Soapy SDR plug-in for Red Pitaya SDR transceiver
* Copyright (C) 2015 Pavel Demin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <sstream>
#include <stdexcept>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include "SoapySDR/Device.hpp"
#include "SoapySDR/Registry.hpp"
#if defined(__APPLE__) || defined(__MACH__)
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL SO_NOSIGPIPE
#endif
#endif
using namespace std;
/***********************************************************************
* Device interface
**********************************************************************/
class SoapyRedPitaya : public SoapySDR::Device
{
public:
SoapyRedPitaya(const SoapySDR::Kwargs &args):
_addr("192.168.1.100"), _port(1001),
_freq(6.0e5), _rate(1.0e5), _corr(0.0)
{
#ifdef _WIN32
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
_sockets[0] = -1;
_sockets[1] = -1;
if(args.count("addr")) _addr = args.at("addr");
if(args.count("port")) stringstream(args.at("port")) >> _port;
}
~SoapyRedPitaya()
{
#ifdef _WIN32
WSACleanup();
#endif
}
/*******************************************************************
* Identification API
******************************************************************/
string getDriverKey() const
{
return "redpitaya";
}
string getHardwareKey() const
{
return "redpitaya";
}
SoapySDR::Kwargs getHardwareInfo() const
{
SoapySDR::Kwargs info;
return info;
}
/*******************************************************************
* Channels API
******************************************************************/
size_t getNumChannels(const int direction) const
{
return 1;
}
bool getFullDuplex(const int direction, const size_t channel) const
{
return true;
}
/*******************************************************************
* Stream API
******************************************************************/
vector<string> getStreamFormats(const int direction, const size_t channel) const
{
vector<string> formats;
formats.push_back("CF32");
return formats;
}
string getNativeStreamFormat(const int direction, const size_t channel, double &fullScale) const
{
fullScale = 1.0;
return "CF32";
}
SoapySDR::ArgInfoList getStreamArgsInfo(const int direction, const size_t channel) const
{
SoapySDR::ArgInfoList streamArgs;
return streamArgs;
}
SoapySDR::Stream *setupStream(
const int direction,
const string &format,
const vector<size_t> &channels = vector<size_t>(),
const SoapySDR::Kwargs &args = SoapySDR::Kwargs())
{
stringstream message;
struct sockaddr_in addr;
uint32_t command;
if(format != "CF32") throw runtime_error("setupStream invalid format " + format);
if(direction == SOAPY_SDR_RX)
{
command = 0;
}
if(direction == SOAPY_SDR_TX)
{
command = 2;
}
for(size_t i = 0; i < 2; ++i)
{
if((_sockets[i] = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
throw std::runtime_error("SoapyRedPitaya could not create TCP socket");
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(_addr.c_str());
addr.sin_port = htons(_port);
if(::connect(_sockets[i], (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
message << "SoapyRedPitaya could not connect to " << _addr << ":" << _port;
throw std::runtime_error(message.str());
}
sendCommand(_sockets[i], command);
++command;
}
}
void closeStream(SoapySDR::Stream *stream)
{
::close(_sockets[1]);
_sockets[1] = -1;
::close(_sockets[0]);
_sockets[0] = -1;
}
size_t getStreamMTU(SoapySDR::Stream *stream) const
{
return 2048;
}
int activateStream(
SoapySDR::Stream *stream,
const int flags = 0,
const long long timeNs = 0,
const size_t numElems = 0)
{
return 0;
}
int deactivateStream(
SoapySDR::Stream *stream,
const int flags = 0,
const long long timeNs = 0)
{
return 0;
}
int readStream(
SoapySDR::Stream *stream,
void * const *buffs,
const size_t numElems,
int &flags,
long long &timeNs,
const long timeoutUs = 100000)
{
struct timeval timeout;
fd_set readfds;
int result;
timeout.tv_sec = timeoutUs / 1000000;
timeout.tv_usec = timeoutUs % 1000000;
FD_ZERO(&readfds);
FD_SET(_sockets[1], &readfds);
result = select(_sockets[1] + 1, &readfds, NULL, NULL, &timeout);
if(result < 0) return 0;
if(result == 0) return SOAPY_SDR_TIMEOUT;
return ::recv(_sockets[1], buffs[0], 8 * numElems, MSG_WAITALL) / 8;
}
int writeStream(
SoapySDR::Stream *stream,
const void * const *buffs,
const size_t numElems,
int &flags,
const long long timeNs = 0,
const long timeoutUs = 100000)
{
struct timeval timeout;
fd_set writefds;
int result;
timeout.tv_sec = timeoutUs / 1000000;
timeout.tv_usec = timeoutUs % 1000000;
FD_ZERO(&writefds);
FD_SET(_sockets[1], &writefds);
result = select(_sockets[1] + 1, NULL, &writefds, NULL, &timeout);
if(result < 0) return 0;
if(result == 0) return SOAPY_SDR_TIMEOUT;
return ::send(_sockets[1], buffs[0], 8 * numElems, MSG_NOSIGNAL) / 8;
}
int readStreamStatus(
SoapySDR::Stream *stream,
size_t &chanMask,
int &flags,
long long &timeNs,
const long timeoutUs)
{
return SOAPY_SDR_NOT_SUPPORTED;
}
/*******************************************************************
* Frequency API
******************************************************************/
void setFrequency(const int direction, const size_t channel, const string &name, const double frequency, const SoapySDR::Kwargs &args = SoapySDR::Kwargs())
{
uint32_t command = 0;
if(name == "BB") return;
if(name != "RF") throw runtime_error("setFrequency invalid name " + name);
if(frequency < _rate / 2.0 || frequency > 6.0e7) return;
command = (uint32_t)floor(frequency * (1.0 + _corr * 1.0e-6) + 0.5);
sendCommand(_sockets[0], command);
_freq = frequency;
}
double getFrequency(const int direction, const size_t channel, const string &name) const
{
if(name == "BB") return 0.0;
if(name != "RF") throw runtime_error("getFrequency invalid name " + name);
return _freq;
}
vector<string> listFrequencies(const int direction, const size_t channel) const
{
vector<string> names;
names.push_back("RF");
return names;
}
SoapySDR::RangeList getFrequencyRange(const int direction, const size_t channel, const string &name) const
{
if (name == "BB") return SoapySDR::RangeList(1, SoapySDR::Range(0.0, 0.0));
if (name != "RF") throw runtime_error("getFrequencyRange invalid name " + name);
return SoapySDR::RangeList(1, SoapySDR::Range(_rate / 2.0, 60.0e6));
}
/*******************************************************************
* Sample Rate API
******************************************************************/
void setSampleRate(const int direction, const size_t channel, const double rate)
{
uint32_t command = 0;
if(2.0e4 == rate) command = 0;
else if(5.0e4 == rate) command = 1;
else if(1.0e5 == rate) command = 2;
else if(2.5e5 == rate) command = 3;
else if(5.0e5 == rate) command = 4;
else if(1.25e6 == rate) command = 5;
command |= 1<<28;
sendCommand(_sockets[0], command);
_rate = rate;
}
double getSampleRate(const int direction, const size_t channel) const
{
return _rate;
}
vector<double> listSampleRates(const int direction, const size_t channel) const
{
vector<double> rates;
rates.push_back(2.0e4);
rates.push_back(5.0e4);
rates.push_back(1.0e5);
rates.push_back(2.5e5);
rates.push_back(5.0e5);
rates.push_back(1.25e6);
return rates;
}
private:
string _addr;
unsigned short _port;
double _freq, _rate, _corr;
int _sockets[2];
static void sendCommand(int socket, uint32_t command)
{
ssize_t size;
stringstream message;
size = ::send(socket, &command, sizeof(command), MSG_NOSIGNAL);
if(size != sizeof(command))
{
message << "SoapyRedPitaya sending command failed: " << std::hex << command;
throw std::runtime_error(message.str());
}
}
};
/***********************************************************************
* Find available devices
**********************************************************************/
SoapySDR::KwargsList findSoapyRedPitaya(const SoapySDR::Kwargs &args)
{
vector<SoapySDR::Kwargs> results;
return results;
}
/***********************************************************************
* Make device instance
**********************************************************************/
SoapySDR::Device *makeSoapyRedPitaya(const SoapySDR::Kwargs &args)
{
return new SoapyRedPitaya(args);
}
/***********************************************************************
* Registration
**********************************************************************/
static SoapySDR::Registry registerSoapyRedPitaya("redpitaya", &findSoapyRedPitaya, &makeSoapyRedPitaya, SOAPY_SDR_ABI_VERSION);
<commit_msg>adapt SoapyRedPitaya.cpp to WIN32<commit_after>/*
* SoapyRedPitaya: Soapy SDR plug-in for Red Pitaya SDR transceiver
* Copyright (C) 2015 Pavel Demin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <sstream>
#include <stdexcept>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#if defined(_WIN32) || defined (__CYGWIN__)
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#else
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include "SoapySDR/Device.hpp"
#include "SoapySDR/Registry.hpp"
#if defined(__APPLE__) || defined(__MACH__)
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL SO_NOSIGPIPE
#endif
#endif
using namespace std;
/***********************************************************************
* Device interface
**********************************************************************/
class SoapyRedPitaya : public SoapySDR::Device
{
public:
SoapyRedPitaya(const SoapySDR::Kwargs &args):
_addr("192.168.1.100"), _port(1001),
_freq(6.0e5), _rate(1.0e5), _corr(0.0)
{
#if defined(_WIN32) || defined (__CYGWIN__)
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
_sockets[0] = -1;
_sockets[1] = -1;
if(args.count("addr")) _addr = args.at("addr");
if(args.count("port")) stringstream(args.at("port")) >> _port;
}
~SoapyRedPitaya()
{
#if defined(_WIN32) || defined (__CYGWIN__)
WSACleanup();
#endif
}
/*******************************************************************
* Identification API
******************************************************************/
string getDriverKey() const
{
return "redpitaya";
}
string getHardwareKey() const
{
return "redpitaya";
}
SoapySDR::Kwargs getHardwareInfo() const
{
SoapySDR::Kwargs info;
return info;
}
/*******************************************************************
* Channels API
******************************************************************/
size_t getNumChannels(const int direction) const
{
return 1;
}
bool getFullDuplex(const int direction, const size_t channel) const
{
return true;
}
/*******************************************************************
* Stream API
******************************************************************/
vector<string> getStreamFormats(const int direction, const size_t channel) const
{
vector<string> formats;
formats.push_back("CF32");
return formats;
}
string getNativeStreamFormat(const int direction, const size_t channel, double &fullScale) const
{
fullScale = 1.0;
return "CF32";
}
SoapySDR::ArgInfoList getStreamArgsInfo(const int direction, const size_t channel) const
{
SoapySDR::ArgInfoList streamArgs;
return streamArgs;
}
SoapySDR::Stream *setupStream(
const int direction,
const string &format,
const vector<size_t> &channels = vector<size_t>(),
const SoapySDR::Kwargs &args = SoapySDR::Kwargs())
{
stringstream message;
struct sockaddr_in addr;
uint32_t command;
if(format != "CF32") throw runtime_error("setupStream invalid format " + format);
if(direction == SOAPY_SDR_RX)
{
command = 0;
}
if(direction == SOAPY_SDR_TX)
{
command = 2;
}
for(size_t i = 0; i < 2; ++i)
{
if((_sockets[i] = ::socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
throw runtime_error("SoapyRedPitaya could not create TCP socket");
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(_addr.c_str());
addr.sin_port = htons(_port);
if(::connect(_sockets[i], (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
message << "SoapyRedPitaya could not connect to " << _addr << ":" << _port;
throw runtime_error(message.str());
}
sendCommand(_sockets[i], command);
++command;
}
return 0;
}
void closeStream(SoapySDR::Stream *stream)
{
::close(_sockets[1]);
_sockets[1] = -1;
::close(_sockets[0]);
_sockets[0] = -1;
}
size_t getStreamMTU(SoapySDR::Stream *stream) const
{
return 2048;
}
int activateStream(
SoapySDR::Stream *stream,
const int flags = 0,
const long long timeNs = 0,
const size_t numElems = 0)
{
return 0;
}
int deactivateStream(
SoapySDR::Stream *stream,
const int flags = 0,
const long long timeNs = 0)
{
return 0;
}
int readStream(
SoapySDR::Stream *stream,
void * const *buffs,
const size_t numElems,
int &flags,
long long &timeNs,
const long timeoutUs = 100000)
{
unsigned long size = 0;
struct timeval timeout;
#if defined(_WIN32) || defined (__CYGWIN__)
::ioctlsocket(_sockets[1], FIONREAD, &size);
#else
::ioctl(_sockets[1], FIONREAD, &size);
#endif
if(size < 8 * numElems)
{
timeout.tv_sec = timeoutUs / 1000000;
timeout.tv_usec = timeoutUs % 1000000;
::select(0, 0, 0, 0, &timeout);
#if defined(_WIN32) || defined (__CYGWIN__)
::ioctlsocket(_sockets[1], FIONREAD, &size);
#else
::ioctl(_sockets[1], FIONREAD, &size);
#endif
}
if(size < 8 * numElems) return SOAPY_SDR_TIMEOUT;
#if defined(_WIN32) || defined (__CYGWIN__)
return ::recv(_sockets[1], (char *)buffs[0], 8 * numElems, MSG_WAITALL) / 8;
#else
return ::recv(_sockets[1], buffs[0], 8 * numElems, MSG_WAITALL) / 8;
#endif
}
int writeStream(
SoapySDR::Stream *stream,
const void * const *buffs,
const size_t numElems,
int &flags,
const long long timeNs = 0,
const long timeoutUs = 100000)
{
ssize_t size;
#if defined(_WIN32) || defined (__CYGWIN__)
size = ::send(_sockets[1], (char *)buffs[0], 8 * numElems, 0);
#else
size = ::send(_sockets[1], buffs[0], 8 * numElems, MSG_NOSIGNAL);
#endif
if(size != 8 * numElems)
{
throw runtime_error("writeStream failed");
}
return numElems;
}
int readStreamStatus(
SoapySDR::Stream *stream,
size_t &chanMask,
int &flags,
long long &timeNs,
const long timeoutUs)
{
return SOAPY_SDR_NOT_SUPPORTED;
}
/*******************************************************************
* Frequency API
******************************************************************/
void setFrequency(const int direction, const size_t channel, const string &name, const double frequency, const SoapySDR::Kwargs &args = SoapySDR::Kwargs())
{
uint32_t command = 0;
if(name == "BB") return;
if(name != "RF") throw runtime_error("setFrequency invalid name " + name);
if(frequency < _rate / 2.0 || frequency > 6.0e7) return;
command = (uint32_t)floor(frequency * (1.0 + _corr * 1.0e-6) + 0.5);
sendCommand(_sockets[0], command);
_freq = frequency;
}
double getFrequency(const int direction, const size_t channel, const string &name) const
{
if(name == "BB") return 0.0;
if(name != "RF") throw runtime_error("getFrequency invalid name " + name);
return _freq;
}
vector<string> listFrequencies(const int direction, const size_t channel) const
{
vector<string> names;
names.push_back("RF");
return names;
}
SoapySDR::RangeList getFrequencyRange(const int direction, const size_t channel, const string &name) const
{
if (name == "BB") return SoapySDR::RangeList(1, SoapySDR::Range(0.0, 0.0));
if (name != "RF") throw runtime_error("getFrequencyRange invalid name " + name);
return SoapySDR::RangeList(1, SoapySDR::Range(_rate / 2.0, 60.0e6));
}
/*******************************************************************
* Sample Rate API
******************************************************************/
void setSampleRate(const int direction, const size_t channel, const double rate)
{
uint32_t command = 0;
if(2.0e4 == rate) command = 0;
else if(5.0e4 == rate) command = 1;
else if(1.0e5 == rate) command = 2;
else if(2.5e5 == rate) command = 3;
else if(5.0e5 == rate) command = 4;
else if(1.25e6 == rate) command = 5;
command |= 1<<28;
sendCommand(_sockets[0], command);
_rate = rate;
}
double getSampleRate(const int direction, const size_t channel) const
{
return _rate;
}
vector<double> listSampleRates(const int direction, const size_t channel) const
{
vector<double> rates;
rates.push_back(2.0e4);
rates.push_back(5.0e4);
rates.push_back(1.0e5);
rates.push_back(2.5e5);
rates.push_back(5.0e5);
rates.push_back(1.25e6);
return rates;
}
private:
string _addr;
unsigned short _port;
double _freq, _rate, _corr;
int _sockets[2];
void sendCommand(int socket, uint32_t command)
{
ssize_t size;
stringstream message;
#if defined(_WIN32) || defined (__CYGWIN__)
size = ::send(socket, (char *)&command, sizeof(command), 0);
#else
size = ::send(socket, &command, sizeof(command), MSG_NOSIGNAL);
#endif
if(size != sizeof(command))
{
message << "sendCommand failed: " << hex << command;
throw runtime_error(message.str());
}
}
};
/***********************************************************************
* Find available devices
**********************************************************************/
SoapySDR::KwargsList findSoapyRedPitaya(const SoapySDR::Kwargs &args)
{
vector<SoapySDR::Kwargs> results;
return results;
}
/***********************************************************************
* Make device instance
**********************************************************************/
SoapySDR::Device *makeSoapyRedPitaya(const SoapySDR::Kwargs &args)
{
return new SoapyRedPitaya(args);
}
/***********************************************************************
* Registration
**********************************************************************/
static SoapySDR::Registry registerSoapyRedPitaya("redpitaya", &findSoapyRedPitaya, &makeSoapyRedPitaya, SOAPY_SDR_ABI_VERSION);
<|endoftext|> |
<commit_before>/* Copyright 2016 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/core/distributed_runtime/rpc/grpc_tensor_coding.h"
#include "grpcpp/support/byte_buffer.h"
#include "grpcpp/support/slice.h"
#include "tensorflow/core/common_runtime/dma_helper.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/tensor_reference.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/lib/io/proto_encode_helper.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/protobuf/worker.pb.h"
namespace tensorflow {
namespace grpc {
void EncodeRecvTensorResponseToByteBuffer(const RecvTensorResponse& proto,
::grpc::ByteBuffer* result) {
::grpc::Slice slice(proto.ByteSizeLong());
proto.SerializeWithCachedSizesToArray(
const_cast<uint8*>(reinterpret_cast<const uint8*>(slice.begin())));
::grpc::ByteBuffer tmp(&slice, 1);
result->Swap(&tmp);
}
// We generate a RecvTensorResponse protocol buffer encoding into "*result",
// but where possible, we share the underlying Tensor buffer for "val", to
// avoid an extra copy.
//
// We hand-encode the protocol buffer data in the following order, as follows:
//
// Let R be a RecvTensorResponse object we want to encode, logically
// constructed by filling in data from "is_dead" and "val" and filling
// in a few other fields as well.
//
// (Letters here are used in the code to refer back to which part of the
// encoding the code is generating).
//
// A: <protocol buffer encoding of fields except R.tensor()>
// B1: <tag encoding for RecvTensorResponse::tensor>
// B2: <varint32 length of R.tensor() sub message>
// C: <protocol buffer encoding of R.tensor() except for
// R.tensor().tensor_content()>
// D1: <tag encoding for TensorProto::tensor_content>
// D2: <varint32 length of R.tensor().tensor_content() data>
// E: <actual data for val's representation>
//
// If the tensor data is up to "kLargeTensorBytes", then A
// through E will all be encoded into "*result" in a single grpc::Slice.
//
// If the tensor data is larger than "kLargeTensorBytes", then A through
// D2 will be encoded in one grpc::Slice, and E will be encoded in a second
// grpc::Slice that points to the backing store for the tensor data, to avoid
// copying the tensor data (and the grpc::Slice setup will be arrange so as
// to dereference the underlying tensor data buffer when it is no longer
// needed in the "*result" ByteBuffer).
static int VarLengthEncodingSize(uint32 tag, size_t bytes) {
return core::VarintLength(tag << 3) + core::VarintLength(bytes) + bytes;
}
// Returns an upper bound in bytes of the protocol buffer encoding of
// the "skeleton" of "val" (all the data needed for dtype and the shape,
// but not the actual contents of "val").
static int SkeletonEncodingSizeUpperBound(const Tensor& val) {
static const int kVarintMax64 = 10; // Max length of varint64 encoding
const int ndims = val.shape().dims();
return (2 * kVarintMax64) + // dtype
(ndims * (4 * kVarintMax64)); // Shape: 4 varints per dim
}
// Encode the skeleton for "val" (the encoded TensorProto contents
// (dtype and shape, but not the actual data) into "*e". The backing
// store for "*e" must be of appropriate size to hold this encoding.
static void EncodeSkeleton(const Tensor& val, io::ProtoEncodeHelper* e) {
// Encode val.dtype()
e->WriteUint64(TensorProto::kDtypeFieldNumber, val.dtype());
// Compute length of val.shape() proto encoding
const int ndims = val.shape().dims();
int tensor_shape_bytes = 0;
for (int d = 0; d < ndims; d++) {
int64 dim_size = val.shape().dim_size(d);
tensor_shape_bytes +=
2 + // TensorShapeProto dim tag + varintlength of submessage
1 + // TensorShapeProto_Dim::kSizeFieldNumber
core::VarintLength(dim_size);
}
if (tensor_shape_bytes > 0) {
e->WriteVarlengthBeginning(TensorProto::kTensorShapeFieldNumber,
tensor_shape_bytes);
// Encode val.shape()
for (int d = 0; d < ndims; d++) {
int64 dim_size = val.shape().dim_size(d);
int64 dim_varlen = 1 + // TensorShapeProto_Dim::kSizeFieldNumber
core::VarintLength(dim_size);
e->WriteVarlengthBeginning(TensorShapeProto::kDimFieldNumber, dim_varlen);
e->WriteUint64(TensorShapeProto_Dim::kSizeFieldNumber, dim_size);
}
}
#ifndef NDEBUG
{
// Debug-mode only check to make sure the encoding above is
// identical to the auto-generated protocol buffer encoding.
TensorProto skeleton;
skeleton.set_dtype(val.dtype());
val.shape().AsProto(skeleton.mutable_tensor_shape());
string tensor_except_contents; // tensor() field except contents
skeleton.AppendToString(&tensor_except_contents);
TensorProto skeleton2;
skeleton2.ParseFromString(string(e->data(), e->size()));
string out;
skeleton.AppendToString(&out);
DCHECK_EQ(tensor_except_contents, out) << skeleton.DebugString() << " vs\n"
<< skeleton2.DebugString();
}
#endif
}
void EncodeTensorToByteBuffer(bool is_dead, const Tensor& val,
::grpc::ByteBuffer* result) {
const int kLargeTensorBytes = 1024;
RecvTensorResponse response;
if (is_dead) {
response.set_is_dead(is_dead);
}
response.set_send_start_micros(Env::Default()->NowMicros());
if (!DataTypeCanUseMemcpy(val.dtype())) {
// Straightforward but slow path for complicated kinds of tensor data
// TODO(jeff,sanjay): If this becomes an issue, we could
// go directly from val -> ByteBuffer, with some effort.
val.AsProtoTensorContent(response.mutable_tensor());
// Encode full protocol buffer to a ByteBuffer
EncodeRecvTensorResponseToByteBuffer(response, result);
} else {
// skeleton is the encoded TensorProto contents (dtype and shape), but
// not the actual data
gtl::InlinedVector<char, 128> skeleton(SkeletonEncodingSizeUpperBound(val));
io::ProtoEncodeHelper e_skeleton(skeleton.data(), skeleton.size());
EncodeSkeleton(val, &e_skeleton);
StringPiece tdata = val.tensor_data();
uint32 overall_tensor_proto_bytesize =
(e_skeleton.size() +
VarLengthEncodingSize(TensorProto::kTensorContentFieldNumber,
tdata.size()));
string header; // All of RecvTensorResponse except the tensor() field
response.AppendToString(&header);
size_t expected_size =
(header.size() +
VarLengthEncodingSize(RecvTensorResponse::kTensorFieldNumber,
overall_tensor_proto_bytesize));
// If "tensor_data_is_large == false", we copy the tensor data to the
// end of the buffer we are preparing that holds the rest of the
// RecvTensorResponse protocol buffer.
//
// If "tensor_data_is_large == true", we arrange to share the backing
// store of the data by creating a slice that also points to the
// backing store, with appropriate reference counts to keep the
// backing store alive as needed.
bool tensor_data_is_large = (tdata.size() > kLargeTensorBytes);
size_t encoder_size = expected_size - tdata.size();
// Encode all but the actual "tdata", but including the tag and
// varlength header for the "tdata"
gtl::InlinedVector<char, 1024> space(encoder_size);
io::ProtoEncodeHelper e(space.data(), space.size());
// (A)
e.WriteRawBytes(header);
// (B1) & (B2)
e.WriteVarlengthBeginning(RecvTensorResponse::kTensorFieldNumber,
overall_tensor_proto_bytesize);
// (C)
e.WriteRawBytes(StringPiece(e_skeleton.data(), e_skeleton.size()));
// (D1) & (D2)
e.WriteVarlengthBeginning(TensorProto::kTensorContentFieldNumber,
tdata.size());
// All but the tensor backing store are serialized now
// Now allocate memory and put into the ByteBuffer
::grpc::Slice slices[2];
int num_slices = 0;
{
size_t slice_len = e.size() + (tensor_data_is_large ? 0 : tdata.size());
slices[0] = ::grpc::Slice(slice_len);
memcpy(const_cast<uint8_t*>(slices[0].begin()), e.data(), e.size());
if (!tensor_data_is_large) {
// (E)
memcpy(const_cast<uint8_t*>(slices[0].begin()) + e.size(), tdata.data(),
tdata.size());
}
num_slices += 1;
}
if (tensor_data_is_large) {
// (E) Encode tensor data, but by sharing backing store
const TensorBuffer* buf = DMAHelper::buffer(&val);
buf->Ref();
slices[1] = ::grpc::Slice(
const_cast<void*>(static_cast<const void*>(tdata.data())),
tdata.size(),
[](void* backing) { static_cast<TensorBuffer*>(backing)->Unref(); },
const_cast<TensorBuffer*>(buf));
num_slices += 1;
}
size_t total_bytes = 0;
for (int i = 0; i < num_slices; i++) {
total_bytes += slices[i].size();
}
CHECK_EQ(total_bytes, expected_size);
::grpc::ByteBuffer tmp(&slices[0], num_slices);
result->Swap(&tmp);
}
}
} // namespace grpc
} // namespace tensorflow
<commit_msg>Rename tensor_data_is_large to share_tensor_slice_memory<commit_after>/* Copyright 2016 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/core/distributed_runtime/rpc/grpc_tensor_coding.h"
#include "grpcpp/support/byte_buffer.h"
#include "grpcpp/support/slice.h"
#include "tensorflow/core/common_runtime/dma_helper.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/tensor_reference.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/lib/io/proto_encode_helper.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/protobuf/worker.pb.h"
// (Omitted internal-only flag)
namespace tensorflow {
namespace grpc {
void EncodeRecvTensorResponseToByteBuffer(const RecvTensorResponse& proto,
::grpc::ByteBuffer* result) {
::grpc::Slice slice(proto.ByteSizeLong());
proto.SerializeWithCachedSizesToArray(
const_cast<uint8*>(reinterpret_cast<const uint8*>(slice.begin())));
::grpc::ByteBuffer tmp(&slice, 1);
result->Swap(&tmp);
}
// We generate a RecvTensorResponse protocol buffer encoding into "*result",
// but where possible, we share the underlying Tensor buffer for "val", to
// avoid an extra copy.
//
// We hand-encode the protocol buffer data in the following order, as follows:
//
// Let R be a RecvTensorResponse object we want to encode, logically
// constructed by filling in data from "is_dead" and "val" and filling
// in a few other fields as well.
//
// (Letters here are used in the code to refer back to which part of the
// encoding the code is generating).
//
// A: <protocol buffer encoding of fields except R.tensor()>
// B1: <tag encoding for RecvTensorResponse::tensor>
// B2: <varint32 length of R.tensor() sub message>
// C: <protocol buffer encoding of R.tensor() except for
// R.tensor().tensor_content()>
// D1: <tag encoding for TensorProto::tensor_content>
// D2: <varint32 length of R.tensor().tensor_content() data>
// E: <actual data for val's representation>
//
// If the tensor data is up to "kLargeTensorBytes", then A
// through E will all be encoded into "*result" in a single grpc::Slice.
//
// If the tensor data is larger than "kLargeTensorBytes", then A through
// D2 will be encoded in one grpc::Slice, and E will be encoded in a second
// grpc::Slice that points to the backing store for the tensor data, to avoid
// copying the tensor data (and the grpc::Slice setup will be arrange so as
// to dereference the underlying tensor data buffer when it is no longer
// needed in the "*result" ByteBuffer).
static int VarLengthEncodingSize(uint32 tag, size_t bytes) {
return core::VarintLength(tag << 3) + core::VarintLength(bytes) + bytes;
}
// Returns an upper bound in bytes of the protocol buffer encoding of
// the "skeleton" of "val" (all the data needed for dtype and the shape,
// but not the actual contents of "val").
static int SkeletonEncodingSizeUpperBound(const Tensor& val) {
static const int kVarintMax64 = 10; // Max length of varint64 encoding
const int ndims = val.shape().dims();
return (2 * kVarintMax64) + // dtype
(ndims * (4 * kVarintMax64)); // Shape: 4 varints per dim
}
// Encode the skeleton for "val" (the encoded TensorProto contents
// (dtype and shape, but not the actual data) into "*e". The backing
// store for "*e" must be of appropriate size to hold this encoding.
static void EncodeSkeleton(const Tensor& val, io::ProtoEncodeHelper* e) {
// Encode val.dtype()
e->WriteUint64(TensorProto::kDtypeFieldNumber, val.dtype());
// Compute length of val.shape() proto encoding
const int ndims = val.shape().dims();
int tensor_shape_bytes = 0;
for (int d = 0; d < ndims; d++) {
int64 dim_size = val.shape().dim_size(d);
tensor_shape_bytes +=
2 + // TensorShapeProto dim tag + varintlength of submessage
1 + // TensorShapeProto_Dim::kSizeFieldNumber
core::VarintLength(dim_size);
}
if (tensor_shape_bytes > 0) {
e->WriteVarlengthBeginning(TensorProto::kTensorShapeFieldNumber,
tensor_shape_bytes);
// Encode val.shape()
for (int d = 0; d < ndims; d++) {
int64 dim_size = val.shape().dim_size(d);
int64 dim_varlen = 1 + // TensorShapeProto_Dim::kSizeFieldNumber
core::VarintLength(dim_size);
e->WriteVarlengthBeginning(TensorShapeProto::kDimFieldNumber, dim_varlen);
e->WriteUint64(TensorShapeProto_Dim::kSizeFieldNumber, dim_size);
}
}
#ifndef NDEBUG
{
// Debug-mode only check to make sure the encoding above is
// identical to the auto-generated protocol buffer encoding.
TensorProto skeleton;
skeleton.set_dtype(val.dtype());
val.shape().AsProto(skeleton.mutable_tensor_shape());
string tensor_except_contents; // tensor() field except contents
skeleton.AppendToString(&tensor_except_contents);
TensorProto skeleton2;
skeleton2.ParseFromString(string(e->data(), e->size()));
string out;
skeleton.AppendToString(&out);
DCHECK_EQ(tensor_except_contents, out) << skeleton.DebugString() << " vs\n"
<< skeleton2.DebugString();
}
#endif
}
void EncodeTensorToByteBuffer(bool is_dead, const Tensor& val,
::grpc::ByteBuffer* result) {
const int kLargeTensorBytes = 1024;
RecvTensorResponse response;
if (is_dead) {
response.set_is_dead(is_dead);
}
response.set_send_start_micros(Env::Default()->NowMicros());
if (!DataTypeCanUseMemcpy(val.dtype())) {
// Straightforward but slow path for complicated kinds of tensor data
// TODO(jeff,sanjay): If this becomes an issue, we could
// go directly from val -> ByteBuffer, with some effort.
val.AsProtoTensorContent(response.mutable_tensor());
// Encode full protocol buffer to a ByteBuffer
EncodeRecvTensorResponseToByteBuffer(response, result);
} else {
// skeleton is the encoded TensorProto contents (dtype and shape), but
// not the actual data
gtl::InlinedVector<char, 128> skeleton(SkeletonEncodingSizeUpperBound(val));
io::ProtoEncodeHelper e_skeleton(skeleton.data(), skeleton.size());
EncodeSkeleton(val, &e_skeleton);
StringPiece tdata = val.tensor_data();
uint32 overall_tensor_proto_bytesize =
(e_skeleton.size() +
VarLengthEncodingSize(TensorProto::kTensorContentFieldNumber,
tdata.size()));
string header; // All of RecvTensorResponse except the tensor() field
response.AppendToString(&header);
size_t expected_size =
(header.size() +
VarLengthEncodingSize(RecvTensorResponse::kTensorFieldNumber,
overall_tensor_proto_bytesize));
// If "share_tensor_slice_memory == false", we copy the tensor data to
// the end of the buffer we are preparing that holds the rest of the
// RecvTensorResponse protocol buffer.
//
// If "share_tensor_slice_memory == true", we arrange to share the
// backing store of the data by creating a slice that also points to the
// backing store, with appropriate reference counts to keep the
// backing store alive as needed.
//
// We enable this behavior if the tensor is large.
bool share_tensor_slice_memory = (tdata.size() > kLargeTensorBytes);
// (Omitted internal-only conditional)
size_t encoder_size = expected_size - tdata.size();
// Encode all but the actual "tdata", but including the tag and
// varlength header for the "tdata"
gtl::InlinedVector<char, 1024> space(encoder_size);
io::ProtoEncodeHelper e(space.data(), space.size());
// (A)
e.WriteRawBytes(header);
// (B1) & (B2)
e.WriteVarlengthBeginning(RecvTensorResponse::kTensorFieldNumber,
overall_tensor_proto_bytesize);
// (C)
e.WriteRawBytes(StringPiece(e_skeleton.data(), e_skeleton.size()));
// (D1) & (D2)
e.WriteVarlengthBeginning(TensorProto::kTensorContentFieldNumber,
tdata.size());
// All but the tensor backing store are serialized now
// Now allocate memory and put into the ByteBuffer
::grpc::Slice slices[2];
int num_slices = 0;
{
size_t slice_len =
e.size() + (share_tensor_slice_memory ? 0 : tdata.size());
slices[0] = ::grpc::Slice(slice_len);
memcpy(const_cast<uint8_t*>(slices[0].begin()), e.data(), e.size());
if (!share_tensor_slice_memory) {
// (E)
memcpy(const_cast<uint8_t*>(slices[0].begin()) + e.size(), tdata.data(),
tdata.size());
}
num_slices += 1;
}
if (share_tensor_slice_memory) {
// (E) Encode tensor data, but by sharing backing store
const TensorBuffer* buf = DMAHelper::buffer(&val);
buf->Ref();
slices[1] = ::grpc::Slice(
const_cast<void*>(static_cast<const void*>(tdata.data())),
tdata.size(),
[](void* backing) { static_cast<TensorBuffer*>(backing)->Unref(); },
const_cast<TensorBuffer*>(buf));
num_slices += 1;
}
size_t total_bytes = 0;
for (int i = 0; i < num_slices; i++) {
total_bytes += slices[i].size();
}
CHECK_EQ(total_bytes, expected_size);
::grpc::ByteBuffer tmp(&slices[0], num_slices);
result->Swap(&tmp);
}
}
} // namespace grpc
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2020 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/core/profiler/convert/op_stats_to_overview_page.h"
#include <algorithm>
#include <utility>
#include "google/protobuf/any.pb.h"
#include "absl/strings/str_format.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/convert/op_metrics_to_record.h"
#include "tensorflow/core/profiler/convert/op_stats_to_input_pipeline_analysis.h"
#include "tensorflow/core/profiler/protobuf/hardware_types.pb.h"
#include "tensorflow/core/profiler/protobuf/input_pipeline.pb.h"
#include "tensorflow/core/profiler/protobuf/op_metrics.pb.h"
#include "tensorflow/core/profiler/protobuf/op_stats.pb.h"
#include "tensorflow/core/profiler/protobuf/overview_page.pb.h"
#include "tensorflow/core/profiler/utils/math_utils.h"
#include "tensorflow/core/profiler/utils/op_metrics_db_utils.h"
#include "tensorflow/core/profiler/utils/time_utils.h"
namespace tensorflow {
namespace profiler {
namespace {
// If the use of low-precision ops is less than this percentage threshold, a
// statement of suggestion will be made.
constexpr double kLowPrecisionPercentThreshold = 10;
OverviewPageTip MakeOverviewPageTip(const string& text) {
OverviewPageTip tip;
tip.set_link(text);
return tip;
}
string AnchorElement(const string& url, const string& text) {
return absl::StrCat("<a href=\"", url, "\" target=\"_blank\">", text, "</a>");
}
// Makes a recommendation for looking up a document.
// doc_url is expected to be already be escaped suitably for use in an HTML
// attribute.
OverviewPageTip MakeOverviewPageTipDocLink(const string& doc_url,
const string& text) {
OverviewPageTip tip;
tip.set_link(AnchorElement(doc_url, text));
return tip;
}
void ComputeHostTips(OverviewPageRecommendation* re) {
*re->add_host_tips() = MakeOverviewPageTip(
"input_pipeline_analyzer (especially Section 3 for the breakdown of "
"input operations on the Host)");
*re->add_host_tips() = MakeOverviewPageTip(
"trace_viewer (look at the activities on the timeline of each Host "
"Thread near the bottom of the trace view)");
}
void ComputeDeviceTips(HardwareType hardware_type,
OverviewPageRecommendation* re) {
const string& device_name = HardwareType_Name(hardware_type);
string timeline_name =
(hardware_type == tensorflow::profiler::TPU) ? "TPU core" : device_name;
*re->add_device_tips() = MakeOverviewPageTip(absl::StrCat(
"op_profile (identify the time-consuming operations executed on the ",
device_name, ")"));
*re->add_device_tips() = MakeOverviewPageTip(absl::StrCat(
"trace_viewer (look at the activities on the timeline of each ",
timeline_name, " in the trace view)"));
}
void ComputeFaqTips(OverviewPageRecommendation* re) {
*re->add_faq_tips() = MakeOverviewPageTip("Refer to the Cloud tools FAQ");
}
void ComputeDocumentationTips(OverviewPageRecommendation* re) {
*re->add_documentation_tips() = MakeOverviewPageTipDocLink(
"https://www.tensorflow.org/guide/"
"data_performance",
"Better performance with the tf.data API");
}
std::string GeneratePrecisionStatement(const PrecisionStats& precision_stats) {
uint64 total_compute_ps =
precision_stats.compute_16bit_ps() + precision_stats.compute_32bit_ps();
if (total_compute_ps > 0) {
double percent_16bit =
(100.0 * precision_stats.compute_16bit_ps()) / total_compute_ps;
if (percent_16bit < kLowPrecisionPercentThreshold) {
return absl::StrCat(
"Only ", absl::StrFormat("%.1lf", percent_16bit),
"% of device computation is 16 bit. So you might want to replace "
"more 32-bit Ops by 16-bit Ops to improve performance (if the "
"reduced accuracy is acceptable).");
}
}
return "";
}
} // namespace
void SetCommonRecommendation(const string& input_classification,
const string& input_statement,
HardwareType hardware_type,
OverviewPageRecommendation* re) {
re->set_bottleneck(input_classification);
re->set_statement(input_statement);
ComputeHostTips(re);
ComputeDeviceTips(hardware_type, re);
ComputeDocumentationTips(re);
ComputeFaqTips(re);
}
OverviewPageRecommendation ComputeGenericRecommendation(
const BottleneckAnalysis& bottleneck,
const PrecisionStats& precision_stats) {
OverviewPageRecommendation re;
GenericRecommendation generic;
generic.set_kernel_launch_bottleneck(
bottleneck.kernel_launch_classification());
generic.set_kernel_launch_statement(bottleneck.kernel_launch_statement());
generic.set_all_other_bottleneck(bottleneck.all_other_classification());
generic.set_all_other_statement(bottleneck.all_other_statement());
generic.set_precision_statement(GeneratePrecisionStatement(precision_stats));
re.mutable_recommendation()->PackFrom(generic);
return re;
}
OverviewPageAnalysis ComputeAnalysisResult(const OpStats& op_stats) {
OverviewPageAnalysis analysis;
OpMetricsDb metrics_db = CreateTfMetricsDbFromHloMetricsDb(
op_stats.device_op_metrics_db(), /*with_idle=*/false);
uint64 total_device_time_ps = metrics_db.total_time_ps();
constexpr int kNumTopOpsShown = 10;
double device_cumulative_fraction = 0.0;
for (const OpMetrics* metrics :
SortedOpMetricsDb(metrics_db, kNumTopOpsShown)) {
OverviewTfOp* op = analysis.add_top_device_ops();
op->set_name(metrics->name());
op->set_category(metrics->category());
op->set_self_time_fraction(
SafeDivide(metrics->self_time_ps(), total_device_time_ps));
device_cumulative_fraction += op->self_time_fraction();
op->set_cumulative_time_fraction(device_cumulative_fraction);
op->set_flop_rate(
SafeDivide(metrics->flops(), PicosToNanos(metrics->time_ps())));
}
SetRemarks(op_stats, &analysis);
uint64 total_device_compute_ps =
op_stats.device_op_metrics_db().precision_stats().compute_16bit_ps() +
op_stats.device_op_metrics_db().precision_stats().compute_32bit_ps();
analysis.set_device_compute_16bit_percent(
100.0 *
SafeDivide(
op_stats.device_op_metrics_db().precision_stats().compute_16bit_ps(),
total_device_compute_ps));
analysis.set_device_compute_32bit_percent(
100.0 *
SafeDivide(
op_stats.device_op_metrics_db().precision_stats().compute_32bit_ps(),
total_device_compute_ps));
return analysis;
}
// Converts from HostIndependentJobInfo to OverviewPageHostIndependentJobInfo.
OverviewPageHostIndependentJobInfo ToOverviewPageHostIndependentJobInfo(
const HostIndependentJobInfoResult& host_independent_job_info) {
OverviewPageHostIndependentJobInfo result;
result.set_change_list(host_independent_job_info.change_list());
result.set_build_time(host_independent_job_info.build_time());
result.set_build_target(host_independent_job_info.build_target());
result.set_profile_duration_ms(
host_independent_job_info.profile_duration_ms());
return result;
}
// Converts from HostDependentJobInfo to OverviewPageHostDependentJobInfo.
OverviewPageHostDependentJobInfo ToOverviewPageHostDependentJobInfo(
const HostDependentJobInfoResult& host_dependent_job_info) {
OverviewPageHostDependentJobInfo result;
result.set_host_id(host_dependent_job_info.host_id());
result.set_command_line(host_dependent_job_info.command_line());
result.set_start_time(host_dependent_job_info.start_time());
result.set_bns_address(host_dependent_job_info.bns_address());
result.set_profile_time_ns(host_dependent_job_info.profile_time_ns());
return result;
}
OverviewPageRunEnvironment ComputeRunEnvironment(
const RunEnvironment& run_environment) {
OverviewPageRunEnvironment re;
re.set_host_count(run_environment.host_count());
re.set_task_count(run_environment.task_count());
re.set_device_type(run_environment.device_type());
re.set_device_core_count(run_environment.device_core_count());
re.set_per_core_batch_size(run_environment.per_core_batch_size());
re.set_replica_count(run_environment.replica_count());
re.set_num_cores_per_replica(run_environment.num_cores_per_replica());
*re.mutable_host_independent_job_info() =
ToOverviewPageHostIndependentJobInfo(
run_environment.host_independent_job_info());
for (const auto& host_dependent_job_info :
run_environment.host_dependent_job_info()) {
*re.add_host_dependent_job_info() =
ToOverviewPageHostDependentJobInfo(host_dependent_job_info);
}
return re;
}
OverviewPage ConvertOpStatsToOverviewPage(const OpStats& op_stats,
HardwareType hardware_type) {
OverviewPageAnalysis analysis = ComputeAnalysisResult(op_stats);
InputPipelineAnalysisResult input_analysis =
ConvertOpStatsToInputPipelineAnalysis(op_stats, hardware_type);
BottleneckAnalysis bottleneck =
ComputeBottleneckAnalysis(input_analysis.step_details());
OverviewPageRecommendation recommendation = ComputeGenericRecommendation(
bottleneck, op_stats.device_op_metrics_db().precision_stats());
SetCommonRecommendation(bottleneck.input_classification(),
bottleneck.input_statement(), hardware_type,
&recommendation);
OverviewPage overview_page;
*overview_page.mutable_run_environment() =
ComputeRunEnvironment(op_stats.run_environment());
*overview_page.mutable_analysis() = analysis;
*overview_page.mutable_input_analysis() = input_analysis;
*overview_page.mutable_recommendation() = recommendation;
return overview_page;
}
void SetRemarks(const OpStats& op_stats, OverviewPageAnalysis* analysis) {
if (op_stats.step_db().step_sequence_size() == 0) {
analysis->set_remark_text(
"WARNING: No step markers observed and hence the step time is actually "
"unknown. This may happen if your profiling duration is shorter than "
"the step time. In that case, you may try to profile longer.");
analysis->set_remark_color("red");
} else {
analysis->set_remark_text("");
analysis->set_remark_color("black");
}
}
} // namespace profiler
} // namespace tensorflow
<commit_msg>Fix some recommendations in the Profiler Overview Page.<commit_after>/* Copyright 2020 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/core/profiler/convert/op_stats_to_overview_page.h"
#include <algorithm>
#include <utility>
#include "google/protobuf/any.pb.h"
#include "absl/strings/str_format.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/profiler/convert/op_metrics_to_record.h"
#include "tensorflow/core/profiler/convert/op_stats_to_input_pipeline_analysis.h"
#include "tensorflow/core/profiler/protobuf/hardware_types.pb.h"
#include "tensorflow/core/profiler/protobuf/input_pipeline.pb.h"
#include "tensorflow/core/profiler/protobuf/op_metrics.pb.h"
#include "tensorflow/core/profiler/protobuf/op_stats.pb.h"
#include "tensorflow/core/profiler/protobuf/overview_page.pb.h"
#include "tensorflow/core/profiler/utils/math_utils.h"
#include "tensorflow/core/profiler/utils/op_metrics_db_utils.h"
#include "tensorflow/core/profiler/utils/time_utils.h"
namespace tensorflow {
namespace profiler {
namespace {
// If the use of low-precision ops is less than this percentage threshold, a
// statement of suggestion will be made.
constexpr double kLowPrecisionPercentThreshold = 10;
OverviewPageTip MakeOverviewPageTip(const string& text) {
OverviewPageTip tip;
tip.set_link(text);
return tip;
}
string AnchorElement(const string& url, const string& text) {
return absl::StrCat("<a href=\"", url, "\" target=\"_blank\">", text, "</a>");
}
// Makes a recommendation for looking up a document.
// doc_url is expected to be already be escaped suitably for use in an HTML
// attribute.
OverviewPageTip MakeOverviewPageTipDocLink(const string& doc_url,
const string& text) {
OverviewPageTip tip;
tip.set_link(AnchorElement(doc_url, text));
return tip;
}
void ComputeHostTips(OverviewPageRecommendation* re) {
*re->add_host_tips() = MakeOverviewPageTip(
"input_pipeline_analyzer (especially Section 3 for the breakdown of "
"input operations on the Host)");
*re->add_host_tips() = MakeOverviewPageTip(
"trace_viewer (look at the activities on the timeline of each Host "
"Thread near the bottom of the trace view)");
}
void ComputeDeviceTips(HardwareType hardware_type,
OverviewPageRecommendation* re) {
const string& device_name = HardwareType_Name(hardware_type);
string timeline_name =
(hardware_type == tensorflow::profiler::TPU) ? "TPU core" : device_name;
string op_stats_toolname = (hardware_type == tensorflow::profiler::TPU)
? "op_profile"
: "tensorflow_stats";
*re->add_device_tips() = MakeOverviewPageTip(
absl::StrCat(op_stats_toolname,
" (identify the time-consuming operations "
"executed on the ",
device_name, ")"));
*re->add_device_tips() = MakeOverviewPageTip(absl::StrCat(
"trace_viewer (look at the activities on the timeline of each ",
timeline_name, " in the trace view)"));
}
void ComputeFaqTips(OverviewPageRecommendation* re) {
*re->add_faq_tips() = MakeOverviewPageTip("Refer to the TF2 Profiler FAQ");
}
void ComputeDocumentationTips(OverviewPageRecommendation* re) {
*re->add_documentation_tips() = MakeOverviewPageTipDocLink(
"https://www.tensorflow.org/guide/"
"data_performance",
"Better performance with the tf.data API");
}
std::string GeneratePrecisionStatement(const PrecisionStats& precision_stats) {
uint64 total_compute_ps =
precision_stats.compute_16bit_ps() + precision_stats.compute_32bit_ps();
if (total_compute_ps > 0) {
double percent_16bit =
(100.0 * precision_stats.compute_16bit_ps()) / total_compute_ps;
if (percent_16bit < kLowPrecisionPercentThreshold) {
return absl::StrCat(
"Only ", absl::StrFormat("%.1lf", percent_16bit),
"% of device computation is 16 bit. So you might want to replace "
"more 32-bit Ops by 16-bit Ops to improve performance (if the "
"reduced accuracy is acceptable).");
}
}
return "";
}
} // namespace
void SetCommonRecommendation(const string& input_classification,
const string& input_statement,
HardwareType hardware_type,
OverviewPageRecommendation* re) {
re->set_bottleneck(input_classification);
re->set_statement(input_statement);
ComputeHostTips(re);
ComputeDeviceTips(hardware_type, re);
ComputeDocumentationTips(re);
ComputeFaqTips(re);
}
OverviewPageRecommendation ComputeGenericRecommendation(
const BottleneckAnalysis& bottleneck,
const PrecisionStats& precision_stats) {
OverviewPageRecommendation re;
GenericRecommendation generic;
generic.set_kernel_launch_bottleneck(
bottleneck.kernel_launch_classification());
generic.set_kernel_launch_statement(bottleneck.kernel_launch_statement());
generic.set_all_other_bottleneck(bottleneck.all_other_classification());
generic.set_all_other_statement(bottleneck.all_other_statement());
generic.set_precision_statement(GeneratePrecisionStatement(precision_stats));
re.mutable_recommendation()->PackFrom(generic);
return re;
}
OverviewPageAnalysis ComputeAnalysisResult(const OpStats& op_stats) {
OverviewPageAnalysis analysis;
OpMetricsDb metrics_db = CreateTfMetricsDbFromHloMetricsDb(
op_stats.device_op_metrics_db(), /*with_idle=*/false);
uint64 total_device_time_ps = metrics_db.total_time_ps();
constexpr int kNumTopOpsShown = 10;
double device_cumulative_fraction = 0.0;
for (const OpMetrics* metrics :
SortedOpMetricsDb(metrics_db, kNumTopOpsShown)) {
OverviewTfOp* op = analysis.add_top_device_ops();
op->set_name(metrics->name());
op->set_category(metrics->category());
op->set_self_time_fraction(
SafeDivide(metrics->self_time_ps(), total_device_time_ps));
device_cumulative_fraction += op->self_time_fraction();
op->set_cumulative_time_fraction(device_cumulative_fraction);
op->set_flop_rate(
SafeDivide(metrics->flops(), PicosToNanos(metrics->time_ps())));
}
SetRemarks(op_stats, &analysis);
uint64 total_device_compute_ps =
op_stats.device_op_metrics_db().precision_stats().compute_16bit_ps() +
op_stats.device_op_metrics_db().precision_stats().compute_32bit_ps();
analysis.set_device_compute_16bit_percent(
100.0 *
SafeDivide(
op_stats.device_op_metrics_db().precision_stats().compute_16bit_ps(),
total_device_compute_ps));
analysis.set_device_compute_32bit_percent(
100.0 *
SafeDivide(
op_stats.device_op_metrics_db().precision_stats().compute_32bit_ps(),
total_device_compute_ps));
return analysis;
}
// Converts from HostIndependentJobInfo to OverviewPageHostIndependentJobInfo.
OverviewPageHostIndependentJobInfo ToOverviewPageHostIndependentJobInfo(
const HostIndependentJobInfoResult& host_independent_job_info) {
OverviewPageHostIndependentJobInfo result;
result.set_change_list(host_independent_job_info.change_list());
result.set_build_time(host_independent_job_info.build_time());
result.set_build_target(host_independent_job_info.build_target());
result.set_profile_duration_ms(
host_independent_job_info.profile_duration_ms());
return result;
}
// Converts from HostDependentJobInfo to OverviewPageHostDependentJobInfo.
OverviewPageHostDependentJobInfo ToOverviewPageHostDependentJobInfo(
const HostDependentJobInfoResult& host_dependent_job_info) {
OverviewPageHostDependentJobInfo result;
result.set_host_id(host_dependent_job_info.host_id());
result.set_command_line(host_dependent_job_info.command_line());
result.set_start_time(host_dependent_job_info.start_time());
result.set_bns_address(host_dependent_job_info.bns_address());
result.set_profile_time_ns(host_dependent_job_info.profile_time_ns());
return result;
}
OverviewPageRunEnvironment ComputeRunEnvironment(
const RunEnvironment& run_environment) {
OverviewPageRunEnvironment re;
re.set_host_count(run_environment.host_count());
re.set_task_count(run_environment.task_count());
re.set_device_type(run_environment.device_type());
re.set_device_core_count(run_environment.device_core_count());
re.set_per_core_batch_size(run_environment.per_core_batch_size());
re.set_replica_count(run_environment.replica_count());
re.set_num_cores_per_replica(run_environment.num_cores_per_replica());
*re.mutable_host_independent_job_info() =
ToOverviewPageHostIndependentJobInfo(
run_environment.host_independent_job_info());
for (const auto& host_dependent_job_info :
run_environment.host_dependent_job_info()) {
*re.add_host_dependent_job_info() =
ToOverviewPageHostDependentJobInfo(host_dependent_job_info);
}
return re;
}
OverviewPage ConvertOpStatsToOverviewPage(const OpStats& op_stats,
HardwareType hardware_type) {
OverviewPageAnalysis analysis = ComputeAnalysisResult(op_stats);
InputPipelineAnalysisResult input_analysis =
ConvertOpStatsToInputPipelineAnalysis(op_stats, hardware_type);
BottleneckAnalysis bottleneck =
ComputeBottleneckAnalysis(input_analysis.step_details());
OverviewPageRecommendation recommendation = ComputeGenericRecommendation(
bottleneck, op_stats.device_op_metrics_db().precision_stats());
SetCommonRecommendation(bottleneck.input_classification(),
bottleneck.input_statement(), hardware_type,
&recommendation);
OverviewPage overview_page;
*overview_page.mutable_run_environment() =
ComputeRunEnvironment(op_stats.run_environment());
*overview_page.mutable_analysis() = analysis;
*overview_page.mutable_input_analysis() = input_analysis;
*overview_page.mutable_recommendation() = recommendation;
return overview_page;
}
void SetRemarks(const OpStats& op_stats, OverviewPageAnalysis* analysis) {
if (op_stats.step_db().step_sequence_size() == 0) {
analysis->set_remark_text(
"WARNING: No step markers observed and hence the step time is actually "
"unknown. This may happen if your profiling duration is shorter than "
"the step time. In that case, you may try to profile longer.");
analysis->set_remark_color("red");
} else {
analysis->set_remark_text("");
analysis->set_remark_color("black");
}
}
} // namespace profiler
} // namespace tensorflow
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
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 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., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreViewport.h"
#include "OgreLogManager.h"
#include "OgreRenderTarget.h"
#include "OgreCamera.h"
#include "OgreMath.h"
#include "OgreRoot.h"
#include "OgreMaterialManager.h"
namespace Ogre {
//---------------------------------------------------------------------
Viewport::Viewport(Camera* cam, RenderTarget* target, Real left, Real top, Real width, Real height, int ZOrder)
: mCamera(cam)
, mTarget(target)
, mRelLeft(left)
, mRelTop(top)
, mRelWidth(width)
, mRelHeight(height)
// Actual dimensions will update later
, mZOrder(ZOrder)
, mBackColour(ColourValue::Black)
, mClearEveryFrame(true)
, mClearBuffers(FBT_COLOUR | FBT_DEPTH)
, mUpdated(false)
, mShowOverlays(true)
, mShowSkies(true)
, mShowShadows(true)
, mVisibilityMask(0xFFFFFFFF)
, mRQSequence(0)
, mMaterialSchemeName(MaterialManager::DEFAULT_SCHEME_NAME)
{
LogManager::getSingleton().stream(LML_TRIVIAL)
<< "Creating viewport on target '" << target->getName() << "'"
<< ", rendering from camera '" << (cam != 0 ? cam->getName() : "NULL") << "'"
<< ", relative dimensions " << std::ios::fixed << std::setprecision(2)
<< "L: " << left << " T: " << top << " W: " << width << " H: " << height
<< " ZOrder: " << ZOrder;
// Calculate actual dimensions
_updateDimensions();
// notify camera
if(cam) cam->_notifyViewport(this);
}
//---------------------------------------------------------------------
Viewport::~Viewport()
{
}
//---------------------------------------------------------------------
bool Viewport::_isUpdated(void) const
{
return mUpdated;
}
//---------------------------------------------------------------------
void Viewport::_clearUpdatedFlag(void)
{
mUpdated = false;
}
//---------------------------------------------------------------------
void Viewport::_updateDimensions(void)
{
Real height = (Real) mTarget->getHeight();
Real width = (Real) mTarget->getWidth();
mActLeft = (int) (mRelLeft * width);
mActTop = (int) (mRelTop * height);
mActWidth = (int) (mRelWidth * width);
mActHeight = (int) (mRelHeight * height);
// This will check if the cameras getAutoAspectRation() property is set.
// If it's true its aspect ratio is fit to the current viewport
// If it's false the camera remains unchanged.
// This allows cameras to be used to render to many viewports,
// which can have their own dimensions and aspect ratios.
if (mCamera && mCamera->getAutoAspectRatio())
{
mCamera->setAspectRatio((Real) mActWidth / (Real) mActHeight);
}
LogManager::getSingleton().stream(LML_TRIVIAL)
<< "Viewport for camera '" << (mCamera != 0 ? mCamera->getName() : "NULL") << "'"
<< ", actual dimensions " << std::ios::fixed << std::setprecision(2)
<< "L: " << mActLeft << " T: " << mActTop << " W: " << mActWidth << " H: " << mActHeight;
mUpdated = true;
}
//---------------------------------------------------------------------
int Viewport::getZOrder(void) const
{
return mZOrder;
}
//---------------------------------------------------------------------
RenderTarget* Viewport::getTarget(void) const
{
return mTarget;
}
//---------------------------------------------------------------------
Camera* Viewport::getCamera(void) const
{
return mCamera;
}
//---------------------------------------------------------------------
Real Viewport::getLeft(void) const
{
return mRelLeft;
}
//---------------------------------------------------------------------
Real Viewport::getTop(void) const
{
return mRelTop;
}
//---------------------------------------------------------------------
Real Viewport::getWidth(void) const
{
return mRelWidth;
}
//---------------------------------------------------------------------
Real Viewport::getHeight(void) const
{
return mRelHeight;
}
//---------------------------------------------------------------------
int Viewport::getActualLeft(void) const
{
return mActLeft;
}
//---------------------------------------------------------------------
int Viewport::getActualTop(void) const
{
return mActTop;
}
//---------------------------------------------------------------------
int Viewport::getActualWidth(void) const
{
return mActWidth;
}
//---------------------------------------------------------------------
int Viewport::getActualHeight(void) const
{
return mActHeight;
}
//---------------------------------------------------------------------
void Viewport::setDimensions(Real left, Real top, Real width, Real height)
{
mRelLeft = left;
mRelTop = top;
mRelWidth = width;
mRelHeight = height;
_updateDimensions();
}
//---------------------------------------------------------------------
void Viewport::update(void)
{
if (mCamera)
{
// Tell Camera to render into me
mCamera->_renderScene(this, mShowOverlays);
}
}
//---------------------------------------------------------------------
void Viewport::setBackgroundColour(const ColourValue& colour)
{
mBackColour = colour;
}
//---------------------------------------------------------------------
const ColourValue& Viewport::getBackgroundColour(void) const
{
return mBackColour;
}
//---------------------------------------------------------------------
void Viewport::setClearEveryFrame(bool clear, unsigned int buffers)
{
mClearEveryFrame = clear;
mClearBuffers = buffers;
}
//---------------------------------------------------------------------
bool Viewport::getClearEveryFrame(void) const
{
return mClearEveryFrame;
}
//---------------------------------------------------------------------
unsigned int Viewport::getClearBuffers(void) const
{
return mClearBuffers;
}
//---------------------------------------------------------------------
void Viewport::getActualDimensions(int &left, int&top, int &width, int &height) const
{
left = mActLeft;
top = mActTop;
width = mActWidth;
height = mActHeight;
}
//---------------------------------------------------------------------
unsigned int Viewport::_getNumRenderedFaces(void) const
{
return mCamera ? mCamera->_getNumRenderedFaces() : 0;
}
//---------------------------------------------------------------------
unsigned int Viewport::_getNumRenderedBatches(void) const
{
return mCamera ? mCamera->_getNumRenderedBatches() : 0;
}
//---------------------------------------------------------------------
void Viewport::setCamera(Camera* cam)
{
mCamera = cam;
if(cam) mCamera->_notifyViewport(this);
}
//---------------------------------------------------------------------
void Viewport::setOverlaysEnabled(bool enabled)
{
mShowOverlays = enabled;
}
//---------------------------------------------------------------------
bool Viewport::getOverlaysEnabled(void) const
{
return mShowOverlays;
}
//---------------------------------------------------------------------
void Viewport::setSkiesEnabled(bool enabled)
{
mShowSkies = enabled;
}
//---------------------------------------------------------------------
bool Viewport::getSkiesEnabled(void) const
{
return mShowSkies;
}
//---------------------------------------------------------------------
void Viewport::setShadowsEnabled(bool enabled)
{
mShowShadows = enabled;
}
//---------------------------------------------------------------------
bool Viewport::getShadowsEnabled(void) const
{
return mShowShadows;
}
//-----------------------------------------------------------------------
void Viewport::setRenderQueueInvocationSequenceName(const String& sequenceName)
{
mRQSequenceName = sequenceName;
if (mRQSequenceName.empty())
{
mRQSequence = 0;
}
else
{
mRQSequence =
Root::getSingleton().getRenderQueueInvocationSequence(mRQSequenceName);
}
}
//-----------------------------------------------------------------------
const String& Viewport::getRenderQueueInvocationSequenceName(void) const
{
return mRQSequenceName;
}
//-----------------------------------------------------------------------
RenderQueueInvocationSequence* Viewport::_getRenderQueueInvocationSequence(void)
{
return mRQSequence;
}
//-----------------------------------------------------------------------
}
<commit_msg>Patch 2500036 - make sure aspect ratio of camera is updated when camera newly assigned to a viewport<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
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 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., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreViewport.h"
#include "OgreLogManager.h"
#include "OgreRenderTarget.h"
#include "OgreCamera.h"
#include "OgreMath.h"
#include "OgreRoot.h"
#include "OgreMaterialManager.h"
namespace Ogre {
//---------------------------------------------------------------------
Viewport::Viewport(Camera* cam, RenderTarget* target, Real left, Real top, Real width, Real height, int ZOrder)
: mCamera(cam)
, mTarget(target)
, mRelLeft(left)
, mRelTop(top)
, mRelWidth(width)
, mRelHeight(height)
// Actual dimensions will update later
, mZOrder(ZOrder)
, mBackColour(ColourValue::Black)
, mClearEveryFrame(true)
, mClearBuffers(FBT_COLOUR | FBT_DEPTH)
, mUpdated(false)
, mShowOverlays(true)
, mShowSkies(true)
, mShowShadows(true)
, mVisibilityMask(0xFFFFFFFF)
, mRQSequence(0)
, mMaterialSchemeName(MaterialManager::DEFAULT_SCHEME_NAME)
{
LogManager::getSingleton().stream(LML_TRIVIAL)
<< "Creating viewport on target '" << target->getName() << "'"
<< ", rendering from camera '" << (cam != 0 ? cam->getName() : "NULL") << "'"
<< ", relative dimensions " << std::ios::fixed << std::setprecision(2)
<< "L: " << left << " T: " << top << " W: " << width << " H: " << height
<< " ZOrder: " << ZOrder;
// Calculate actual dimensions
_updateDimensions();
// notify camera
if(cam) cam->_notifyViewport(this);
}
//---------------------------------------------------------------------
Viewport::~Viewport()
{
}
//---------------------------------------------------------------------
bool Viewport::_isUpdated(void) const
{
return mUpdated;
}
//---------------------------------------------------------------------
void Viewport::_clearUpdatedFlag(void)
{
mUpdated = false;
}
//---------------------------------------------------------------------
void Viewport::_updateDimensions(void)
{
Real height = (Real) mTarget->getHeight();
Real width = (Real) mTarget->getWidth();
mActLeft = (int) (mRelLeft * width);
mActTop = (int) (mRelTop * height);
mActWidth = (int) (mRelWidth * width);
mActHeight = (int) (mRelHeight * height);
// This will check if the cameras getAutoAspectRation() property is set.
// If it's true its aspect ratio is fit to the current viewport
// If it's false the camera remains unchanged.
// This allows cameras to be used to render to many viewports,
// which can have their own dimensions and aspect ratios.
if (mCamera && mCamera->getAutoAspectRatio())
{
mCamera->setAspectRatio((Real) mActWidth / (Real) mActHeight);
}
LogManager::getSingleton().stream(LML_TRIVIAL)
<< "Viewport for camera '" << (mCamera != 0 ? mCamera->getName() : "NULL") << "'"
<< ", actual dimensions " << std::ios::fixed << std::setprecision(2)
<< "L: " << mActLeft << " T: " << mActTop << " W: " << mActWidth << " H: " << mActHeight;
mUpdated = true;
}
//---------------------------------------------------------------------
int Viewport::getZOrder(void) const
{
return mZOrder;
}
//---------------------------------------------------------------------
RenderTarget* Viewport::getTarget(void) const
{
return mTarget;
}
//---------------------------------------------------------------------
Camera* Viewport::getCamera(void) const
{
return mCamera;
}
//---------------------------------------------------------------------
Real Viewport::getLeft(void) const
{
return mRelLeft;
}
//---------------------------------------------------------------------
Real Viewport::getTop(void) const
{
return mRelTop;
}
//---------------------------------------------------------------------
Real Viewport::getWidth(void) const
{
return mRelWidth;
}
//---------------------------------------------------------------------
Real Viewport::getHeight(void) const
{
return mRelHeight;
}
//---------------------------------------------------------------------
int Viewport::getActualLeft(void) const
{
return mActLeft;
}
//---------------------------------------------------------------------
int Viewport::getActualTop(void) const
{
return mActTop;
}
//---------------------------------------------------------------------
int Viewport::getActualWidth(void) const
{
return mActWidth;
}
//---------------------------------------------------------------------
int Viewport::getActualHeight(void) const
{
return mActHeight;
}
//---------------------------------------------------------------------
void Viewport::setDimensions(Real left, Real top, Real width, Real height)
{
mRelLeft = left;
mRelTop = top;
mRelWidth = width;
mRelHeight = height;
_updateDimensions();
}
//---------------------------------------------------------------------
void Viewport::update(void)
{
if (mCamera)
{
// Tell Camera to render into me
mCamera->_renderScene(this, mShowOverlays);
}
}
//---------------------------------------------------------------------
void Viewport::setBackgroundColour(const ColourValue& colour)
{
mBackColour = colour;
}
//---------------------------------------------------------------------
const ColourValue& Viewport::getBackgroundColour(void) const
{
return mBackColour;
}
//---------------------------------------------------------------------
void Viewport::setClearEveryFrame(bool clear, unsigned int buffers)
{
mClearEveryFrame = clear;
mClearBuffers = buffers;
}
//---------------------------------------------------------------------
bool Viewport::getClearEveryFrame(void) const
{
return mClearEveryFrame;
}
//---------------------------------------------------------------------
unsigned int Viewport::getClearBuffers(void) const
{
return mClearBuffers;
}
//---------------------------------------------------------------------
void Viewport::getActualDimensions(int &left, int&top, int &width, int &height) const
{
left = mActLeft;
top = mActTop;
width = mActWidth;
height = mActHeight;
}
//---------------------------------------------------------------------
unsigned int Viewport::_getNumRenderedFaces(void) const
{
return mCamera ? mCamera->_getNumRenderedFaces() : 0;
}
//---------------------------------------------------------------------
unsigned int Viewport::_getNumRenderedBatches(void) const
{
return mCamera ? mCamera->_getNumRenderedBatches() : 0;
}
//---------------------------------------------------------------------
void Viewport::setCamera(Camera* cam)
{
mCamera = cam;
_updateDimensions();
if(cam) mCamera->_notifyViewport(this);
}
//---------------------------------------------------------------------
void Viewport::setOverlaysEnabled(bool enabled)
{
mShowOverlays = enabled;
}
//---------------------------------------------------------------------
bool Viewport::getOverlaysEnabled(void) const
{
return mShowOverlays;
}
//---------------------------------------------------------------------
void Viewport::setSkiesEnabled(bool enabled)
{
mShowSkies = enabled;
}
//---------------------------------------------------------------------
bool Viewport::getSkiesEnabled(void) const
{
return mShowSkies;
}
//---------------------------------------------------------------------
void Viewport::setShadowsEnabled(bool enabled)
{
mShowShadows = enabled;
}
//---------------------------------------------------------------------
bool Viewport::getShadowsEnabled(void) const
{
return mShowShadows;
}
//-----------------------------------------------------------------------
void Viewport::setRenderQueueInvocationSequenceName(const String& sequenceName)
{
mRQSequenceName = sequenceName;
if (mRQSequenceName.empty())
{
mRQSequence = 0;
}
else
{
mRQSequence =
Root::getSingleton().getRenderQueueInvocationSequence(mRQSequenceName);
}
}
//-----------------------------------------------------------------------
const String& Viewport::getRenderQueueInvocationSequenceName(void) const
{
return mRQSequenceName;
}
//-----------------------------------------------------------------------
RenderQueueInvocationSequence* Viewport::_getRenderQueueInvocationSequence(void)
{
return mRQSequence;
}
//-----------------------------------------------------------------------
}
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2015 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <gtest/gtest.h>
#include <repo/core/model/bson/repo_node_metadata.h>
#include <repo/core/model/bson/repo_bson_builder.h>
#include <repo/core/model/bson/repo_bson_factory.h>
#include "../../../../repo_test_utils.h"
using namespace repo::core::model;
static MetadataNode makeRandomMetaNode()
{
uint32_t nItems = rand() % 10 + 1;
std::vector<std::string> keys, values;
for (int i = 0; i < nItems; ++i)
{
keys.push_back(getRandomString(rand() % 10 + 1));
values.push_back(getRandomString(rand() % 10 + 1));
}
return RepoBSONFactory::makeMetaDataNode(keys, values);
}
/**
* Construct from mongo builder and mongo bson should give me the same bson
*/
TEST(MetaNodeTest, Constructor)
{
MetadataNode empty;
EXPECT_TRUE(empty.isEmpty());
EXPECT_EQ(NodeType::METADATA, empty.getTypeAsEnum());
auto repoBson = RepoBSON(BSON("test" << "blah" << "test2" << 2));
auto fromRepoBSON = MetadataNode(repoBson);
EXPECT_EQ(NodeType::METADATA, fromRepoBSON.getTypeAsEnum());
EXPECT_EQ(fromRepoBSON.nFields(), repoBson.nFields());
EXPECT_EQ(0, fromRepoBSON.getFileList().size());
}
TEST(MetaNodeTest, TypeTest)
{
MetadataNode node;
EXPECT_EQ(REPO_NODE_TYPE_METADATA, node.getType());
EXPECT_EQ(NodeType::METADATA, node.getTypeAsEnum());
}
TEST(MetaNodeTest, PositionDependantTest)
{
MetadataNode node;
EXPECT_FALSE(node.positionDependant());
}
TEST(MetaNodeTest, SEqualTest)
{
MetadataNode empty;
EXPECT_TRUE(empty.sEqual(empty));
auto metaNode = makeRandomMetaNode();
auto metaNode2 = makeRandomMetaNode();
EXPECT_TRUE(metaNode.sEqual(metaNode));
EXPECT_FALSE(metaNode.sEqual(empty));
EXPECT_FALSE(metaNode.sEqual(metaNode2));
}
TEST(MetaNodeTest, CloneAndAddMetadataTest)
{
MetadataNode empty;
auto metaNode = makeRandomMetaNode();
auto metaNode2 = makeRandomMetaNode();
auto meta1 = metaNode.getObjectField(REPO_NODE_LABEL_METADATA);
auto meta2 = metaNode2.getObjectField(REPO_NODE_LABEL_METADATA);
auto updatedMeta = empty.cloneAndAddMetadata(meta1);
updatedMeta.sEqual(metaNode);
auto updatedMeta2 = updatedMeta.cloneAndAddMetadata(meta2);
auto resMeta = updatedMeta2.getObjectField(REPO_NODE_LABEL_METADATA);
std::set<std::string> fieldNames1, fieldNames2;
meta1.getFieldNames(fieldNames1);
meta2.getFieldNames(fieldNames2);
for (const auto &fieldName : fieldNames1)
{
ASSERT_TRUE(resMeta.hasField(fieldName));
EXPECT_EQ(resMeta.getField(fieldName), meta1.getField(fieldName));
}
for (const auto &fieldName : fieldNames2)
{
ASSERT_TRUE(resMeta.hasField(fieldName));
EXPECT_EQ(resMeta.getField(fieldName), meta2.getField(fieldName));
}
}<commit_msg>#13 travis fix<commit_after>/**
* Copyright (C) 2015 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <gtest/gtest.h>
#include <repo/core/model/bson/repo_node_metadata.h>
#include <repo/core/model/bson/repo_bson_builder.h>
#include <repo/core/model/bson/repo_bson_factory.h>
#include "../../../../repo_test_utils.h"
using namespace repo::core::model;
static MetadataNode makeRandomMetaNode()
{
uint32_t nItems = rand() % 10 + 1;
std::vector<std::string> keys, values;
for (int i = 0; i < nItems; ++i)
{
keys.push_back(getRandomString(rand() % 10 + 1));
values.push_back(getRandomString(rand() % 10 + 1));
}
return RepoBSONFactory::makeMetaDataNode(keys, values);
}
/**
* Construct from mongo builder and mongo bson should give me the same bson
*/
TEST(MetaNodeTest, Constructor)
{
MetadataNode empty;
EXPECT_TRUE(empty.isEmpty());
EXPECT_EQ(NodeType::METADATA, empty.getTypeAsEnum());
auto repoBson = RepoBSON(BSON("test" << "blah" << "test2" << 2));
auto fromRepoBSON = MetadataNode(repoBson);
EXPECT_EQ(NodeType::METADATA, fromRepoBSON.getTypeAsEnum());
EXPECT_EQ(fromRepoBSON.nFields(), repoBson.nFields());
EXPECT_EQ(0, fromRepoBSON.getFileList().size());
}
TEST(MetaNodeTest, TypeTest)
{
MetadataNode node;
EXPECT_EQ(REPO_NODE_TYPE_METADATA, node.getType());
EXPECT_EQ(NodeType::METADATA, node.getTypeAsEnum());
}
TEST(MetaNodeTest, PositionDependantTest)
{
MetadataNode node;
EXPECT_FALSE(node.positionDependant());
}
TEST(MetaNodeTest, SEqualTest)
{
MetadataNode empty;
EXPECT_TRUE(empty.sEqual(empty));
auto metaNode = makeRandomMetaNode();
auto metaNode2 = makeRandomMetaNode();
EXPECT_TRUE(metaNode.sEqual(metaNode));
EXPECT_FALSE(metaNode.sEqual(empty));
EXPECT_FALSE(metaNode.sEqual(metaNode2));
}
TEST(MetaNodeTest, CloneAndAddMetadataTest)
{
MetadataNode empty;
auto metaNode = makeRandomMetaNode();
auto metaNode2 = makeRandomMetaNode();
auto meta1 = metaNode.getObjectField(REPO_NODE_LABEL_METADATA);
auto meta2 = metaNode2.getObjectField(REPO_NODE_LABEL_METADATA);
auto updatedMeta = empty.cloneAndAddMetadata(meta1);
updatedMeta.sEqual(metaNode);
auto updatedMeta2 = updatedMeta.cloneAndAddMetadata(meta2);
auto resMeta = updatedMeta2.getObjectField(REPO_NODE_LABEL_METADATA);
std::set<std::string> fieldNames1, fieldNames2;
meta1.getFieldNames(fieldNames1);
meta2.getFieldNames(fieldNames2);
for (const auto &fieldName : fieldNames1)
{
//Skip the ones that would be overwritten
if (meta2.hasField(fieldName)) continue;
ASSERT_TRUE(resMeta.hasField(fieldName));
EXPECT_EQ(resMeta.getField(fieldName), meta1.getField(fieldName));
}
for (const auto &fieldName : fieldNames2)
{
ASSERT_TRUE(resMeta.hasField(fieldName));
EXPECT_EQ(resMeta.getField(fieldName), meta2.getField(fieldName));
}
}<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#ifdef __GNUC__
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#else
#include <filesystem>
namespace fs = std::tr2::sys;
#endif
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/face.hpp>
#define CONFIG_NUM_WORKERS 2
#define CONFIG_FACE_CLASS 41
cv::Ptr<cv::face::BasicFaceRecognizer> make_recognizer(int argc, char *argv[]) {
std::vector<cv::Mat> images;
std::vector<int> labels;
// iterate through subdirectories to locate .pgm files
fs::path p(argc > 1 ? argv[1] : "../assets/faces");
for(const auto &entry : fs::recursive_directory_iterator{p}) {
if(fs::is_regular_file(entry.status())) {
if(entry.path().extension() == ".pgm") {
std::string str = entry.path().parent_path().stem().string();
int label = atoi(str.c_str() + 1);
images.push_back(cv::imread(entry.path().string().c_str(), 0));
labels.push_back(label);
}
}
}
auto recognizer = cv::face::createEigenFaceRecognizer();
recognizer->train(images, labels);
return recognizer;
}
void camera_loop(boost::shared_ptr<boost::asio::io_service> service,
cv::VideoCapture vid,
cv::Ptr<cv::face::BasicFaceRecognizer> recognizer,
unsigned int count) {
cv::Mat frame;
vid >> frame;
float actual_aspect = (float)frame.cols / (float)frame.rows;
float target_aspect = 92.0f / 112.0f;
int target_width = frame.cols, target_height = frame.rows;
if(actual_aspect > target_aspect) {
target_width = target_height * target_aspect;
} else {
target_height = target_width / target_aspect;
}
cv::Rect rect(frame.cols / 2 - target_width / 2,
frame.rows / 2 - target_height / 2,
target_width, target_height);
cv::Mat cropped_frame = frame(rect);
cv::Mat gray_frame, resized_frame;
cv::cvtColor(cropped_frame, gray_frame, CV_RGB2GRAY);
cv::resize(gray_frame, resized_frame, cv::Size(92, 112));
int predicted = recognizer->predict(resized_frame);
if(predicted == CONFIG_FACE_CLASS) {
if(count < 10) { ++count; }
} else {
if(count > 0) { --count; }
}
cv::Mat flipped_frame;
cv::flip(cropped_frame, flipped_frame, 1);
cv::Rect color_rect(0, 0, flipped_frame.cols, flipped_frame.rows);
cv::rectangle(flipped_frame, color_rect, cv::Scalar(0, 0, 0), 10);
switch(count) {
case 0:
cv::rectangle(flipped_frame, color_rect, cv::Scalar(0, 0, 255), 8);
break;
case 10:
cv::rectangle(flipped_frame, color_rect, cv::Scalar(0, 255, 0), 8);
break;
default:
cv::rectangle(flipped_frame, color_rect, cv::Scalar(0, 255, 255), 8);
break;
}
cv::rectangle(flipped_frame, color_rect, cv::Scalar(0, 0, 0), 2);
cv::imshow("optflow", flipped_frame);
cv::waitKey(1000/60);
service->post(std::bind(camera_loop, service, vid, recognizer, count));
}
void camera_main(boost::shared_ptr<boost::asio::io_service> service,
cv::Ptr<cv::face::BasicFaceRecognizer> recognizer) {
cv::VideoCapture vid(0);
if(!vid.isOpened()) {
throw std::runtime_error("failed to open video capture device");
}
cv::namedWindow("optflow");
service->post(std::bind(camera_loop, service, vid, recognizer, 0));
}
void worker_main(boost::shared_ptr<boost::asio::io_service> service) {
service->run();
}
int main(int argc, char *argv[]) {
std::cout << "training..." << std::endl;
auto recognizer = make_recognizer(argc, argv);
std::cout << "done" << std::endl;
auto service = boost::make_shared<boost::asio::io_service>();
auto work = boost::make_shared<boost::asio::io_service::work>(*service);
auto strand = boost::make_shared<boost::asio::io_service::strand>(*service);
boost::thread_group workers;
for(unsigned int w = 0; w < CONFIG_NUM_WORKERS; ++w) {
workers.create_thread(boost::bind(worker_main, service));
}
service->post(boost::bind(camera_main, service, recognizer));
work.reset();
workers.join_all();
return 0;
}
<commit_msg>main: tidy up rectangle drawing code<commit_after>#include <iostream>
#include <fstream>
#ifdef __GNUC__
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#else
#include <filesystem>
namespace fs = std::tr2::sys;
#endif
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/face.hpp>
#define CONFIG_NUM_WORKERS 2
#define CONFIG_FACE_CLASS 41
cv::Ptr<cv::face::BasicFaceRecognizer> make_recognizer(int argc, char *argv[]) {
std::vector<cv::Mat> images;
std::vector<int> labels;
// iterate through subdirectories to locate .pgm files
fs::path p(argc > 1 ? argv[1] : "../assets/faces");
for(const auto &entry : fs::recursive_directory_iterator{p}) {
if(fs::is_regular_file(entry.status())) {
if(entry.path().extension() == ".pgm") {
std::string str = entry.path().parent_path().stem().string();
int label = atoi(str.c_str() + 1);
images.push_back(cv::imread(entry.path().string().c_str(), 0));
labels.push_back(label);
}
}
}
auto recognizer = cv::face::createEigenFaceRecognizer();
recognizer->train(images, labels);
return recognizer;
}
void camera_loop(boost::shared_ptr<boost::asio::io_service> service,
cv::VideoCapture vid,
cv::Ptr<cv::face::BasicFaceRecognizer> recognizer,
unsigned int count) {
cv::Mat frame;
vid >> frame;
float actual_aspect = (float)frame.cols / (float)frame.rows;
float target_aspect = 92.0f / 112.0f;
int target_width = frame.cols, target_height = frame.rows;
if(actual_aspect > target_aspect) {
target_width = target_height * target_aspect;
} else {
target_height = target_width / target_aspect;
}
cv::Rect rect(frame.cols / 2 - target_width / 2,
frame.rows / 2 - target_height / 2,
target_width, target_height);
cv::Mat cropped_frame = frame(rect);
cv::Mat gray_frame, resized_frame;
cv::cvtColor(cropped_frame, gray_frame, CV_RGB2GRAY);
cv::resize(gray_frame, resized_frame, cv::Size(92, 112));
int predicted = recognizer->predict(resized_frame);
if(predicted == CONFIG_FACE_CLASS) {
if(count < 10) { ++count; }
} else {
if(count > 0) { --count; }
}
cv::Mat flipped_frame;
cv::flip(cropped_frame, flipped_frame, 1);
cv::Rect color_rect(0, 0, flipped_frame.cols, flipped_frame.rows);
cv::Scalar color(0, 255, 255);
switch(count) {
case 0:
color = cv::Scalar(0, 0, 255);
break;
case 10:
color = cv::Scalar(0, 255, 0);
break;
}
cv::rectangle(flipped_frame, color_rect, cv::Scalar(0), 10);
cv::rectangle(flipped_frame, color_rect, color, 8);
cv::rectangle(flipped_frame, color_rect, cv::Scalar(0), 2);
cv::imshow("optflow", flipped_frame);
cv::waitKey(1000/60);
service->post(std::bind(camera_loop, service, vid, recognizer, count));
}
void camera_main(boost::shared_ptr<boost::asio::io_service> service,
cv::Ptr<cv::face::BasicFaceRecognizer> recognizer) {
cv::VideoCapture vid(0);
if(!vid.isOpened()) {
throw std::runtime_error("failed to open video capture device");
}
cv::namedWindow("optflow");
service->post(std::bind(camera_loop, service, vid, recognizer, 0));
}
void worker_main(boost::shared_ptr<boost::asio::io_service> service) {
service->run();
}
int main(int argc, char *argv[]) {
std::cout << "training..." << std::endl;
auto recognizer = make_recognizer(argc, argv);
std::cout << "done" << std::endl;
auto service = boost::make_shared<boost::asio::io_service>();
auto work = boost::make_shared<boost::asio::io_service::work>(*service);
auto strand = boost::make_shared<boost::asio::io_service::strand>(*service);
boost::thread_group workers;
for(unsigned int w = 0; w < CONFIG_NUM_WORKERS; ++w) {
workers.create_thread(boost::bind(worker_main, service));
}
service->post(boost::bind(camera_main, service, recognizer));
work.reset();
workers.join_all();
return 0;
}
<|endoftext|> |
<commit_before>#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <queue>
#include <stdio.h>
#include <math.h>
#include "constants.h"
#include "findEyeCenter.h"
#include "findEyeCorner.h"
/** Constants **/
/** Function Headers */
void detectAndDisplay( cv::Mat frame );
/** Global variables */
//-- Note, either copy these two files from opencv/data/haarscascades to your current folder, or change these locations
cv::String face_cascade_name = "../../../res/haarcascade_frontalface_alt.xml";
cv::CascadeClassifier face_cascade;
std::string main_window_name = "Capture - Face detection";
std::string face_window_name = "Capture - Face";
cv::RNG rng(12345);
cv::Mat debugImage;
cv::Mat skinCrCbHist = cv::Mat::zeros(cv::Size(256, 256), CV_8UC1);
/**
* @function main
*/
int main( int argc, const char** argv ) {
CvCapture* capture;
cv::Mat frame;
// Load the cascades
if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading face cascade, please change face_cascade_name in source code.\n"); return -1; };
cv::namedWindow(main_window_name,CV_WINDOW_NORMAL);
cv::moveWindow(main_window_name, 400, 100);
cv::namedWindow(face_window_name,CV_WINDOW_NORMAL);
cv::moveWindow(face_window_name, 10, 100);
cv::namedWindow("Right Eye",CV_WINDOW_NORMAL);
cv::moveWindow("Right Eye", 10, 600);
cv::namedWindow("Left Eye",CV_WINDOW_NORMAL);
cv::moveWindow("Left Eye", 10, 800);
cv::namedWindow("aa",CV_WINDOW_NORMAL);
cv::moveWindow("aa", 10, 800);
cv::namedWindow("aaa",CV_WINDOW_NORMAL);
cv::moveWindow("aaa", 10, 800);
createCornerKernels();
ellipse(skinCrCbHist, cv::Point(113, 155.6), cv::Size(23.4, 15.2),
43.0, 0.0, 360.0, cv::Scalar(255, 255, 255), -1);
// Read the video stream
capture = cvCaptureFromCAM( -1 );
if( capture ) {
while( true ) {
frame = cvQueryFrame( capture );
// mirror it
cv::flip(frame, frame, 1);
frame.copyTo(debugImage);
// Apply the classifier to the frame
if( !frame.empty() ) {
detectAndDisplay( frame );
}
else {
printf(" --(!) No captured frame -- Break!");
break;
}
imshow(main_window_name,debugImage);
int c = cv::waitKey(10);
if( (char)c == 'c' ) { break; }
if( (char)c == 'f' ) {
imwrite("frame.png",frame);
}
}
}
releaseCornerKernels();
return 0;
}
void findEyes(cv::Mat frame_gray, cv::Rect face) {
cv::Mat faceROI = frame_gray(face);
cv::Mat debugFace = faceROI;
if (kSmoothFaceImage) {
double sigma = kSmoothFaceFactor * face.width;
GaussianBlur( faceROI, faceROI, cv::Size( 0, 0 ), sigma);
}
//-- Find eye regions and draw them
int eye_region_width = face.width * (kEyePercentWidth/100.0);
int eye_region_height = face.width * (kEyePercentHeight/100.0);
int eye_region_top = face.height * (kEyePercentTop/100.0);
cv::Rect leftEyeRegion(face.width*(kEyePercentSide/100.0),
eye_region_top,eye_region_width,eye_region_height);
cv::Rect rightEyeRegion(face.width - eye_region_width - face.width*(kEyePercentSide/100.0),
eye_region_top,eye_region_width,eye_region_height);
//-- Find Eye Centers
cv::Point leftPupil = findEyeCenter(faceROI,leftEyeRegion,"Left Eye");
cv::Point rightPupil = findEyeCenter(faceROI,rightEyeRegion,"Right Eye");
// get corner regions
cv::Rect leftRightCornerRegion(leftEyeRegion);
leftRightCornerRegion.width -= leftPupil.x;
leftRightCornerRegion.x += leftPupil.x;
leftRightCornerRegion.height /= 2;
leftRightCornerRegion.y += leftRightCornerRegion.height / 2;
cv::Rect leftLeftCornerRegion(leftEyeRegion);
leftLeftCornerRegion.width = leftPupil.x;
leftLeftCornerRegion.height /= 2;
leftLeftCornerRegion.y += leftLeftCornerRegion.height / 2;
cv::Rect rightLeftCornerRegion(rightEyeRegion);
rightLeftCornerRegion.width = rightPupil.x;
rightLeftCornerRegion.height /= 2;
rightLeftCornerRegion.y += rightLeftCornerRegion.height / 2;
cv::Rect rightRightCornerRegion(rightEyeRegion);
rightRightCornerRegion.width -= rightPupil.x;
rightRightCornerRegion.x += rightPupil.x;
rightRightCornerRegion.height /= 2;
rightRightCornerRegion.y += rightRightCornerRegion.height / 2;
rectangle(debugFace,leftRightCornerRegion,200);
rectangle(debugFace,leftLeftCornerRegion,200);
rectangle(debugFace,rightLeftCornerRegion,200);
rectangle(debugFace,rightRightCornerRegion,200);
// change eye centers to face coordinates
rightPupil.x += rightEyeRegion.x;
rightPupil.y += rightEyeRegion.y;
leftPupil.x += leftEyeRegion.x;
leftPupil.y += leftEyeRegion.y;
// draw eye centers
circle(debugFace, rightPupil, 3, 1234);
circle(debugFace, leftPupil, 3, 1234);
//-- Find Eye Corners
if (kEnableEyeCorner) {
cv::Point2f leftRightCorner = findEyeCorner(faceROI(leftRightCornerRegion), true, false);
leftRightCorner.x += leftRightCornerRegion.x;
leftRightCorner.y += leftRightCornerRegion.y;
cv::Point2f leftLeftCorner = findEyeCorner(faceROI(leftLeftCornerRegion), true, true);
leftLeftCorner.x += leftLeftCornerRegion.x;
leftLeftCorner.y += leftLeftCornerRegion.y;
cv::Point2f rightLeftCorner = findEyeCorner(faceROI(rightLeftCornerRegion), false, true);
rightLeftCorner.x += rightLeftCornerRegion.x;
rightLeftCorner.y += rightLeftCornerRegion.y;
cv::Point2f rightRightCorner = findEyeCorner(faceROI(rightRightCornerRegion), false, false);
rightRightCorner.x += rightRightCornerRegion.x;
rightRightCorner.y += rightRightCornerRegion.y;
circle(faceROI, leftRightCorner, 3, 200);
circle(faceROI, leftLeftCorner, 3, 200);
circle(faceROI, rightLeftCorner, 3, 200);
circle(faceROI, rightRightCorner, 3, 200);
}
imshow(face_window_name, faceROI);
// cv::Rect roi( cv::Point( 0, 0 ), faceROI.size());
// cv::Mat destinationROI = debugImage( roi );
// faceROI.copyTo( destinationROI );
}
cv::Mat findSkin (cv::Mat &frame) {
cv::Mat input;
cv::Mat output = cv::Mat(frame.rows,frame.cols, CV_8U);
cvtColor(frame, input, CV_BGR2YCrCb);
for (int y = 0; y < input.rows; ++y) {
const cv::Vec3b *Mr = input.ptr<cv::Vec3b>(y);
// uchar *Or = output.ptr<uchar>(y);
cv::Vec3b *Or = frame.ptr<cv::Vec3b>(y);
for (int x = 0; x < input.cols; ++x) {
cv::Vec3b ycrcb = Mr[x];
// Or[x] = (skinCrCbHist.at<uchar>(ycrcb[1], ycrcb[2]) > 0) ? 255 : 0;
if(skinCrCbHist.at<uchar>(ycrcb[1], ycrcb[2]) == 0) {
Or[x] = cv::Vec3b(0,0,0);
}
}
}
return output;
}
/**
* @function detectAndDisplay
*/
void detectAndDisplay( cv::Mat frame ) {
std::vector<cv::Rect> faces;
//cv::Mat frame_gray;
std::vector<cv::Mat> rgbChannels(3);
cv::split(frame, rgbChannels);
cv::Mat frame_gray = rgbChannels[2];
//cvtColor( frame, frame_gray, CV_BGR2GRAY );
//equalizeHist( frame_gray, frame_gray );
//cv::pow(frame_gray, CV_64F, frame_gray);
//-- Detect faces
face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE|CV_HAAR_FIND_BIGGEST_OBJECT, cv::Size(150, 150) );
// findSkin(debugImage);
for( int i = 0; i < faces.size(); i++ )
{
rectangle(debugImage, faces[i], 1234);
}
//-- Show what you got
if (faces.size() > 0) {
findEyes(frame_gray, faces[0]);
}
}
<commit_msg>added color blob tracking to the app<commit_after>#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <queue>
#include <stdio.h>
#include <math.h>
#include <vector>
#include "constants.h"
#include "findEyeCenter.h"
#include "findEyeCorner.h"
using namespace std;
using namespace cv;
/** Constants **/
/** Function Headers */
void detectAndDisplay( cv::Mat frame );
void findFacialMarkers( cv::Mat frame);
/** Global variables */
//-- Note, either copy these two files from opencv/data/haarscascades to your current folder, or change these locations
cv::String face_cascade_name = "../../res/haarcascade_frontalface_alt.xml";
cv::CascadeClassifier face_cascade;
std::string main_window_name = "Capture - Face detection";
std::string face_window_name = "Capture - Face";
std::string markers_window_name = "Capture - Facial Markers";
cv::RNG rng(12345);
cv::Mat debugImage;
cv::Mat skinCrCbHist = cv::Mat::zeros(cv::Size(256, 256), CV_8UC1);
int iLowH = 48;
int iHighH = 65;
int iLowS = 115;
int iHighS = 255;
int iLowV = 178;
int iHighV = 247;
/**
* @function main
*/
int main( int argc, const char** argv ) {
CvCapture* capture;
cv::Mat frame;
// Load the cascades
if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading face cascade, please change face_cascade_name in source code.\n"); return -1; };
cv::namedWindow(main_window_name,CV_WINDOW_NORMAL);
cv::moveWindow(main_window_name, 400, 100);
cv::namedWindow(face_window_name,CV_WINDOW_NORMAL);
cv::moveWindow(face_window_name, 10, 100);
cv::namedWindow(markers_window_name,CV_WINDOW_NORMAL);
cv::moveWindow(markers_window_name, 800, 100);
cv::namedWindow("Right Eye",CV_WINDOW_NORMAL);
cv::moveWindow("Right Eye", 10, 600);
cv::namedWindow("Left Eye",CV_WINDOW_NORMAL);
cv::moveWindow("Left Eye", 10, 800);
// Add trackbars for the HSV settings
cvCreateTrackbar("LowH", markers_window_name.c_str(), &iLowH, 179); //Hue (0 - 179)
cvCreateTrackbar("HighH", markers_window_name.c_str(), &iHighH, 179);
cvCreateTrackbar("LowS", markers_window_name.c_str(), &iLowS, 255); //Saturation (0 - 255)
cvCreateTrackbar("HighS", markers_window_name.c_str(), &iHighS, 255);
cvCreateTrackbar("LowV", markers_window_name.c_str(), &iLowV, 255); //Value (0 - 255)
cvCreateTrackbar("HighV", markers_window_name.c_str(), &iHighV, 255);
createCornerKernels();
ellipse(skinCrCbHist, cv::Point(113, 155.6), cv::Size(23.4, 15.2),
43.0, 0.0, 360.0, cv::Scalar(255, 255, 255), -1);
// Read the video stream
//capture = cvCaptureFromFile("../../res/jc.jpg" );
capture = cvCaptureFromCAM(2);
if( capture ) {
while( true ) {
frame = cvQueryFrame( capture );
cv::flip(frame, frame, 1);
// mirror it
frame.copyTo(debugImage);
// Apply the classifier to the frame
if( !frame.empty() ) {
findFacialMarkers(frame);
detectAndDisplay(frame);
}
else {
printf(" --(!) No captured frame -- Break!");
break;
}
imshow(main_window_name, debugImage);
int c = cv::waitKey(10);
if( (char)c == 'c' ) { break; }
if( (char)c == 'f' ) {
imwrite("frame.png",frame);
}
}
}
releaseCornerKernels();
return 0;
}
void findFacialMarkers(cv::Mat frame) {
vector<vector<cv::Point> > contours;
vector<cv::Vec4i> hierarchy;
cv::Mat imgHSV;
cv::cvtColor(frame, imgHSV, cv::COLOR_RGB2HSV); //Convert the captured frame from RGB to HSV
cv::Mat imgThresholded;
cv::inRange(imgHSV, cv::Scalar(iLowH, iLowS, iLowV), cv::Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image
imshow(markers_window_name.c_str(), imgThresholded);
cv::findContours(imgThresholded, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE, cv::Point(0, 0));
for (int i = 0; i < contours.size(); i++) {
Rect bound = boundingRect(contours[i]);
Point center = Point( bound.x + (bound.width / 2), bound.y + (bound.height / 2));
circle(debugImage, center, 3, Scalar(0, 0, 255), -1);
}
}
void findEyes(cv::Mat frame_gray, cv::Rect face) {
cv::Mat faceROI = frame_gray(face);
cv::Mat debugFace = faceROI;
if (kSmoothFaceImage) {
double sigma = kSmoothFaceFactor * face.width;
GaussianBlur( faceROI, faceROI, cv::Size( 0, 0 ), sigma);
}
//-- Find eye regions and draw them
int eye_region_width = face.width * (kEyePercentWidth/100.0);
int eye_region_height = face.width * (kEyePercentHeight/100.0);
int eye_region_top = face.height * (kEyePercentTop/100.0);
cv::Rect leftEyeRegion(face.width*(kEyePercentSide/100.0),
eye_region_top,eye_region_width,eye_region_height);
cv::Rect rightEyeRegion(face.width - eye_region_width - face.width*(kEyePercentSide/100.0),
eye_region_top,eye_region_width,eye_region_height);
//-- Find Eye Centers
cv::Point leftPupil = findEyeCenter(faceROI,leftEyeRegion,"Left Eye");
cv::Point rightPupil = findEyeCenter(faceROI,rightEyeRegion,"Right Eye");
// get corner regions
cv::Rect leftRightCornerRegion(leftEyeRegion);
leftRightCornerRegion.width -= leftPupil.x;
leftRightCornerRegion.x += leftPupil.x;
leftRightCornerRegion.height /= 2;
leftRightCornerRegion.y += leftRightCornerRegion.height / 2;
cv::Rect leftLeftCornerRegion(leftEyeRegion);
leftLeftCornerRegion.width = leftPupil.x;
leftLeftCornerRegion.height /= 2;
leftLeftCornerRegion.y += leftLeftCornerRegion.height / 2;
cv::Rect rightLeftCornerRegion(rightEyeRegion);
rightLeftCornerRegion.width = rightPupil.x;
rightLeftCornerRegion.height /= 2;
rightLeftCornerRegion.y += rightLeftCornerRegion.height / 2;
cv::Rect rightRightCornerRegion(rightEyeRegion);
rightRightCornerRegion.width -= rightPupil.x;
rightRightCornerRegion.x += rightPupil.x;
rightRightCornerRegion.height /= 2;
rightRightCornerRegion.y += rightRightCornerRegion.height / 2;
rectangle(debugFace,leftRightCornerRegion,200);
rectangle(debugFace,leftLeftCornerRegion,200);
rectangle(debugFace,rightLeftCornerRegion,200);
rectangle(debugFace,rightRightCornerRegion,200);
// change eye centers to face coordinates
rightPupil.x += rightEyeRegion.x;
rightPupil.y += rightEyeRegion.y;
leftPupil.x += leftEyeRegion.x;
leftPupil.y += leftEyeRegion.y;
// draw eye centers
circle(debugFace, rightPupil, 3, 1234);
circle(debugFace, leftPupil, 3, 1234);
//-- Find Eye Corners
if (kEnableEyeCorner) {
cv::Point2f leftRightCorner = findEyeCorner(faceROI(leftRightCornerRegion), true, false);
leftRightCorner.x += leftRightCornerRegion.x;
leftRightCorner.y += leftRightCornerRegion.y;
cv::Point2f leftLeftCorner = findEyeCorner(faceROI(leftLeftCornerRegion), true, true);
leftLeftCorner.x += leftLeftCornerRegion.x;
leftLeftCorner.y += leftLeftCornerRegion.y;
cv::Point2f rightLeftCorner = findEyeCorner(faceROI(rightLeftCornerRegion), false, true);
rightLeftCorner.x += rightLeftCornerRegion.x;
rightLeftCorner.y += rightLeftCornerRegion.y;
cv::Point2f rightRightCorner = findEyeCorner(faceROI(rightRightCornerRegion), false, false);
rightRightCorner.x += rightRightCornerRegion.x;
rightRightCorner.y += rightRightCornerRegion.y;
circle(faceROI, leftRightCorner, 3, 200);
circle(faceROI, leftLeftCorner, 3, 200);
circle(faceROI, rightLeftCorner, 3, 200);
circle(faceROI, rightRightCorner, 3, 200);
}
imshow(face_window_name, faceROI);
// cv::Rect roi( cv::Point( 0, 0 ), faceROI.size());
// cv::Mat destinationROI = debugImage( roi );
// faceROI.copyTo( destinationROI );
}
cv::Mat findSkin (cv::Mat &frame) {
cv::Mat input;
cv::Mat output = cv::Mat(frame.rows,frame.cols, CV_8U);
cvtColor(frame, input, CV_BGR2YCrCb);
for (int y = 0; y < input.rows; ++y) {
const cv::Vec3b *Mr = input.ptr<cv::Vec3b>(y);
// uchar *Or = output.ptr<uchar>(y);
cv::Vec3b *Or = frame.ptr<cv::Vec3b>(y);
for (int x = 0; x < input.cols; ++x) {
cv::Vec3b ycrcb = Mr[x];
// Or[x] = (skinCrCbHist.at<uchar>(ycrcb[1], ycrcb[2]) > 0) ? 255 : 0;
if(skinCrCbHist.at<uchar>(ycrcb[1], ycrcb[2]) == 0) {
Or[x] = cv::Vec3b(0,0,0);
}
}
}
return output;
}
/**
* @function detectAndDisplay
*/
void detectAndDisplay( cv::Mat frame ) {
std::vector<cv::Rect> faces;
//cv::Mat frame_gray;
std::vector<cv::Mat> rgbChannels(3);
cv::split(frame, rgbChannels);
cv::Mat frame_gray = rgbChannels[2]; // Used to be rgbChannels[2], i.e. the blue channel.
//cvtColor( frame, frame_gray, CV_BGR2GRAY );
//equalizeHist( frame_gray, frame_gray );
//cv::pow(frame_gray, CV_64F, frame_gray);
//-- Detect faces
face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE|CV_HAAR_FIND_BIGGEST_OBJECT, cv::Size(150, 150) );
// findSkin(debugImage);
for( int i = 0; i < faces.size(); i++ )
{
rectangle(debugImage, faces[i], 1234);
}
//-- Show what you got
if (faces.size() > 0) {
findEyes(frame_gray, faces[0]);
}
}
<|endoftext|> |
<commit_before>#include "FOX_OSG_MDIView.h"
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/TrackballManipulator>
#include <osgDB/ReadFile>
// Map
FXDEFMAP(FOX_OSG_MDIView) FOX_OSG_MDIView_Map[] = {
//________Message_Type_________ ___ID___ ________Message_Handler________
FXMAPFUNC(SEL_CHORE, FOX_OSG_MDIView::ID_CHORE, FOX_OSG_MDIView::OnIdle)
};
FXIMPLEMENT(FOX_OSG_MDIView, FXMDIChild, FOX_OSG_MDIView_Map, ARRAYNUMBER(FOX_OSG_MDIView_Map))
FOX_OSG_MDIView::FOX_OSG_MDIView(FXMDIClient *p, const FXString &name,
FXIcon *ic, FXPopup *pup, FXuint opt,
FXint x, FXint y, FXint w, FXint h)
: FXMDIChild(p, name, ic, pup, opt, x, y, w, h)
{
// A visual to drag OpenGL in double-buffered mode; note the glvisual is
// shared between all windows which need the same depths and numbers of buffers
// Thus, while the first visual may take some time to initialize, each subsequent
// window can be created very quickly; we need to determine grpaphics hardware
// characteristics only once.
FXGLVisual* glVisual=new FXGLVisual(getApp(),VISUAL_DOUBLEBUFFER|VISUAL_STEREO);
m_gwFox = new GraphicsWindowFOX(this, glVisual, NULL, 0, LAYOUT_FILL_X|LAYOUT_FILL_Y, x, y, w, h );
osgViewer::Viewer *viewer = new osgViewer::Viewer;
viewer->getCamera()->setGraphicsContext(m_gwFox);
viewer->getCamera()->setViewport(0,0,w,h);
viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded);
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile("cow.osg");
if (!loadedModel)
{
return ;
}
// add the stats handler
viewer->addEventHandler(new osgViewer::StatsHandler);
viewer->setSceneData(loadedModel.get());
viewer->setCameraManipulator(new osgGA::TrackballManipulator);
SetViewer(viewer);
getApp()->addChore(this,ID_CHORE);
}
FOX_OSG_MDIView::~FOX_OSG_MDIView()
{
getApp()->removeChore(this,ID_CHORE);
}
long FOX_OSG_MDIView::OnIdle(FXObject *sender, FXSelector sel, void* ptr)
{
m_osgViewer->frame();
getApp()->addChore(this, ID_CHORE);
return 1;
}
void FOX_OSG_MDIView::SetViewer(osgViewer::Viewer* viewer)
{
m_osgViewer = viewer;
}
<commit_msg>Disable the escape sets done on the viewer<commit_after>#include "FOX_OSG_MDIView.h"
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/TrackballManipulator>
#include <osgDB/ReadFile>
// Map
FXDEFMAP(FOX_OSG_MDIView) FOX_OSG_MDIView_Map[] = {
//________Message_Type_________ ___ID___ ________Message_Handler________
FXMAPFUNC(SEL_CHORE, FOX_OSG_MDIView::ID_CHORE, FOX_OSG_MDIView::OnIdle)
};
FXIMPLEMENT(FOX_OSG_MDIView, FXMDIChild, FOX_OSG_MDIView_Map, ARRAYNUMBER(FOX_OSG_MDIView_Map))
FOX_OSG_MDIView::FOX_OSG_MDIView(FXMDIClient *p, const FXString &name,
FXIcon *ic, FXPopup *pup, FXuint opt,
FXint x, FXint y, FXint w, FXint h)
: FXMDIChild(p, name, ic, pup, opt, x, y, w, h)
{
// A visual to drag OpenGL in double-buffered mode; note the glvisual is
// shared between all windows which need the same depths and numbers of buffers
// Thus, while the first visual may take some time to initialize, each subsequent
// window can be created very quickly; we need to determine grpaphics hardware
// characteristics only once.
FXGLVisual* glVisual=new FXGLVisual(getApp(),VISUAL_DOUBLEBUFFER|VISUAL_STEREO);
m_gwFox = new GraphicsWindowFOX(this, glVisual, NULL, 0, LAYOUT_FILL_X|LAYOUT_FILL_Y, x, y, w, h );
osgViewer::Viewer *viewer = new osgViewer::Viewer;
viewer->getCamera()->setGraphicsContext(m_gwFox);
viewer->getCamera()->setViewport(0,0,w,h);
viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded);
// FOX example does not catch the close of the graphics window, so
// don't allow the default escape sets to done to be active.
viewer->setKeyEventSetsDone(0);
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile("cow.osg");
if (!loadedModel)
{
return ;
}
// add the stats handler
viewer->addEventHandler(new osgViewer::StatsHandler);
viewer->setSceneData(loadedModel.get());
viewer->setCameraManipulator(new osgGA::TrackballManipulator);
SetViewer(viewer);
getApp()->addChore(this,ID_CHORE);
}
FOX_OSG_MDIView::~FOX_OSG_MDIView()
{
getApp()->removeChore(this,ID_CHORE);
}
long FOX_OSG_MDIView::OnIdle(FXObject *sender, FXSelector sel, void* ptr)
{
m_osgViewer->frame();
getApp()->addChore(this, ID_CHORE);
return 1;
}
void FOX_OSG_MDIView::SetViewer(osgViewer::Viewer* viewer)
{
m_osgViewer = viewer;
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief イグナイター・アプリケーション・クラス
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "main.hpp"
#include "core/glcore.hpp"
#include "utils/i_scene.hpp"
#include "utils/director.hpp"
#include "widgets/widget.hpp"
#include "widgets/widget_frame.hpp"
#include "widgets/widget_null.hpp"
#include "widgets/widget_button.hpp"
#include "widgets/widget_filer.hpp"
#include "widgets/widget_terminal.hpp"
#include "widgets/widget_view.hpp"
#include "widgets/widget_utils.hpp"
#include "ign_client.hpp"
#include "ign_server.hpp"
#include "render_waves.hpp"
namespace app {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief Ignitor アプリケーション・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class ignitor : public utils::i_scene {
utils::director<core>& director_;
gui::widget_frame* menu_;
gui::widget_button* load_;
gui::widget_filer* load_ctx_;
gui::widget_frame* wave_;
gui::widget_frame* terminal_frame_;
gui::widget_terminal* terminal_core_;
gui::widget_frame* view_frame_;
gui::widget_view* view_core_;
asio::io_service io_service_;
net::ign_client client_;
net::ign_server server_;
bool start_client_;
typedef view::render_waves<uint16_t, 65536 * 4> WAVES;
WAVES waves_;
// ターミナル、行入力
void term_enter_(const utils::lstring& text) {
auto s = utils::utf32_to_utf8(text);
// project_.logic_edit_.command(s);
/// std::cout << s << std::endl;
}
// 波形描画
void update_view_()
{
}
void render_view_(const vtx::irect& clip)
{
glDisable(GL_TEXTURE_2D);
gl::glColor(img::rgba8(255, 255));
waves_.render(clip.size.x);
}
void service_view_()
{
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
ignitor(utils::director<core>& d) : director_(d),
menu_(nullptr), load_(nullptr), load_ctx_(nullptr),
wave_(nullptr),
terminal_frame_(nullptr), terminal_core_(nullptr),
view_frame_(nullptr), view_core_(nullptr),
io_service_(),
client_(io_service_),
server_(io_service_),
start_client_(false)
{
}
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void initialize()
{
using namespace gui;
widget_director& wd = director_.at().widget_director_;
gl::core& core = gl::core::get_instance();
{ // メニューパレット
widget::param wp(vtx::irect(10, 10, 110, 300));
widget_frame::param wp_;
wp_.plate_param_.set_caption(12);
menu_ = wd.add_widget<widget_frame>(wp, wp_);
menu_->set_state(gui::widget::state::SIZE_LOCK);
}
{ // ロード起動ボタン
widget::param wp(vtx::irect(10, 20+40*0, 90, 30), menu_);
widget_button::param wp_("load");
wp_.select_func_ = [this](int id) {
// gui::get_open_file_name();
if(load_ctx_) {
// script_on_ = false;
bool f = load_ctx_->get_state(gui::widget::state::ENABLE);
load_ctx_->enable(!f);
// save_->set_stall(!f);
// export_->set_stall(!f);
// script_->set_stall(!f);
}
};
load_ = wd.add_widget<widget_button>(wp, wp_);
}
{ // load ファイラー本体
widget::param wp(vtx::irect(10, 30, 300, 200));
widget_filer::param wp_(core.get_current_path());
wp_.select_file_func_ = [this](const std::string& path) {
#if 0
bool f = false;
if(script_on_) {
f = project_.logic_edit_.injection(path);
} else {
f = project_.logic_.load(path);
}
load_->set_stall(false);
save_->set_stall(false);
export_->set_stall(false);
script_->set_stall(false);
if(!f) { // load error
if(script_on_) dialog_->set_text("Script error:\n" + path);
else dialog_->set_text("Load error:\n" + path);
dialog_->enable();
}
#endif
};
load_ctx_ = wd.add_widget<widget_filer>(wp, wp_);
load_ctx_->enable(false);
}
{ // ターミナル
{
widget::param wp(vtx::irect(20, 100, 100, 200));
widget_frame::param wp_;
wp_.plate_param_.set_caption(12);
terminal_frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
{
widget::param wp(vtx::irect(0), terminal_frame_);
widget_terminal::param wp_;
wp_.enter_func_ = [this](const utils::lstring& text) {
term_enter_(text);
};
terminal_core_ = wd.add_widget<widget_terminal>(wp, wp_);
term_chaout::set_output(terminal_core_);
}
// ロジック編集クラスの出力先の設定
// project_.logic_edit_.set_output([this](const std::string& s) {
// terminal_core_->output(s);
// }
// );
}
{ // 波形ビュー
{
widget::param wp(vtx::irect(40, 150, 200, 200));
widget_frame::param wp_;
wp_.plate_param_.set_caption(12);
view_frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
{
widget::param wp(vtx::irect(0), view_frame_);
widget_view::param wp_;
wp_.update_func_ = [this]() {
update_view_();
};
wp_.render_func_ = [this](const vtx::irect& clip) {
render_view_(clip);
};
wp_.service_func_ = [this]() {
service_view_();
};
view_core_ = wd.add_widget<widget_view>(wp, wp_);
}
}
// プリファレンスのロード
sys::preference& pre = director_.at().preference_;
if(menu_ != nullptr) {
menu_->load(pre, false, false);
}
/// project_.load(pre);
if(terminal_frame_ != nullptr) {
terminal_frame_->load(pre);
}
if(view_frame_ != nullptr) {
view_frame_->load(pre);
}
// if(argv_frame_ != nullptr) {
// argv_frame_->load(pre);
// }
if(load_ctx_ != nullptr) load_ctx_->load(pre);
/// if(save_ctx_ != nullptr) save_ctx_->load(pre);
/// if(edit_ != nullptr) edit_->load(pre);
// テスト・サーバー起動
server_.start();
// テスト波形生成
waves_.create_waves(0.5, 5.0 * 10e-6);
waves_.create_sin(1000);
}
//-----------------------------------------------------------------//
/*!
@brief アップデート
*/
//-----------------------------------------------------------------//
void update()
{
if(start_client_) {
client_.service();
} else {
client_.start();
start_client_ = true;
}
server_.service();
io_service_.run();
gui::widget_director& wd = director_.at().widget_director_;
#if 0
// Drag & Drop されたファイル
gl::core& core = gl::core::get_instance();
int id = core.get_recv_files_id();
if(drop_file_id_ != id) {
drop_file_id_ = id;
const utils::strings& ss = core.get_recv_files_path();
if(!ss.empty()) {
std::string path = ss[0];
if(load_ctx_ != nullptr && load_ctx_->get_local_param().select_file_func_ != nullptr) {
load_ctx_->get_local_param().select_file_func_(path);
}
}
}
#endif
wd.update();
}
//-----------------------------------------------------------------//
/*!
@brief レンダリング
*/
//-----------------------------------------------------------------//
void render()
{
director_.at().widget_director_.service();
director_.at().widget_director_.render();
}
//-----------------------------------------------------------------//
/*!
@brief 廃棄
*/
//-----------------------------------------------------------------//
void destroy()
{
sys::preference& pre = director_.at().preference_;
/// if(edit_ != nullptr) edit_->save(pre);
if(load_ctx_ != nullptr) load_ctx_->save(pre);
/// if(save_ctx_ != nullptr) save_ctx_->save(pre);
// if(argv_frame_ != nullptr) {
// argv_frame_->save(pre);
// }
if(view_frame_ != nullptr) {
view_frame_->save(pre);
}
if(terminal_frame_ != nullptr) {
terminal_frame_->save(pre);
}
// project_.save(pre);
if(menu_ != nullptr) {
menu_->save(pre);
}
}
};
}
<commit_msg>update sin wave initial<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief イグナイター・アプリケーション・クラス
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "main.hpp"
#include "core/glcore.hpp"
#include "utils/i_scene.hpp"
#include "utils/director.hpp"
#include "widgets/widget.hpp"
#include "widgets/widget_frame.hpp"
#include "widgets/widget_null.hpp"
#include "widgets/widget_button.hpp"
#include "widgets/widget_filer.hpp"
#include "widgets/widget_terminal.hpp"
#include "widgets/widget_view.hpp"
#include "widgets/widget_utils.hpp"
#include "ign_client.hpp"
#include "ign_server.hpp"
#include "gl_fw/render_waves.hpp"
namespace app {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief Ignitor アプリケーション・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class ignitor : public utils::i_scene {
utils::director<core>& director_;
gui::widget_frame* menu_;
gui::widget_button* load_;
gui::widget_filer* load_ctx_;
gui::widget_frame* wave_;
gui::widget_frame* terminal_frame_;
gui::widget_terminal* terminal_core_;
gui::widget_frame* view_frame_;
gui::widget_view* view_core_;
asio::io_service io_service_;
net::ign_client client_;
net::ign_server server_;
bool start_client_;
typedef view::render_waves<uint16_t, 65536 * 4> WAVES;
WAVES waves_;
// ターミナル、行入力
void term_enter_(const utils::lstring& text) {
auto s = utils::utf32_to_utf8(text);
// project_.logic_edit_.command(s);
/// std::cout << s << std::endl;
}
// 波形描画
void update_view_()
{
}
void render_view_(const vtx::irect& clip)
{
glDisable(GL_TEXTURE_2D);
gl::glColor(img::rgba8(255, 255));
waves_.render(clip.size.x);
}
void service_view_()
{
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
ignitor(utils::director<core>& d) : director_(d),
menu_(nullptr), load_(nullptr), load_ctx_(nullptr),
wave_(nullptr),
terminal_frame_(nullptr), terminal_core_(nullptr),
view_frame_(nullptr), view_core_(nullptr),
io_service_(),
client_(io_service_),
server_(io_service_),
start_client_(false)
{
}
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void initialize()
{
using namespace gui;
widget_director& wd = director_.at().widget_director_;
gl::core& core = gl::core::get_instance();
{ // メニューパレット
widget::param wp(vtx::irect(10, 10, 110, 300));
widget_frame::param wp_;
wp_.plate_param_.set_caption(12);
menu_ = wd.add_widget<widget_frame>(wp, wp_);
menu_->set_state(gui::widget::state::SIZE_LOCK);
}
{ // ロード起動ボタン
widget::param wp(vtx::irect(10, 20+40*0, 90, 30), menu_);
widget_button::param wp_("load");
wp_.select_func_ = [this](int id) {
// gui::get_open_file_name();
if(load_ctx_) {
// script_on_ = false;
bool f = load_ctx_->get_state(gui::widget::state::ENABLE);
load_ctx_->enable(!f);
// save_->set_stall(!f);
// export_->set_stall(!f);
// script_->set_stall(!f);
}
};
load_ = wd.add_widget<widget_button>(wp, wp_);
}
{ // load ファイラー本体
widget::param wp(vtx::irect(10, 30, 300, 200));
widget_filer::param wp_(core.get_current_path());
wp_.select_file_func_ = [this](const std::string& path) {
#if 0
bool f = false;
if(script_on_) {
f = project_.logic_edit_.injection(path);
} else {
f = project_.logic_.load(path);
}
load_->set_stall(false);
save_->set_stall(false);
export_->set_stall(false);
script_->set_stall(false);
if(!f) { // load error
if(script_on_) dialog_->set_text("Script error:\n" + path);
else dialog_->set_text("Load error:\n" + path);
dialog_->enable();
}
#endif
};
load_ctx_ = wd.add_widget<widget_filer>(wp, wp_);
load_ctx_->enable(false);
}
{ // ターミナル
{
widget::param wp(vtx::irect(20, 100, 100, 200));
widget_frame::param wp_;
wp_.plate_param_.set_caption(12);
terminal_frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
{
widget::param wp(vtx::irect(0), terminal_frame_);
widget_terminal::param wp_;
wp_.enter_func_ = [this](const utils::lstring& text) {
term_enter_(text);
};
terminal_core_ = wd.add_widget<widget_terminal>(wp, wp_);
term_chaout::set_output(terminal_core_);
}
// ロジック編集クラスの出力先の設定
// project_.logic_edit_.set_output([this](const std::string& s) {
// terminal_core_->output(s);
// }
// );
}
{ // 波形ビュー
{
widget::param wp(vtx::irect(40, 150, 200, 200));
widget_frame::param wp_;
wp_.plate_param_.set_caption(12);
view_frame_ = wd.add_widget<widget_frame>(wp, wp_);
}
{
widget::param wp(vtx::irect(0), view_frame_);
widget_view::param wp_;
wp_.update_func_ = [this]() {
update_view_();
};
wp_.render_func_ = [this](const vtx::irect& clip) {
render_view_(clip);
};
wp_.service_func_ = [this]() {
service_view_();
};
view_core_ = wd.add_widget<widget_view>(wp, wp_);
}
}
// プリファレンスのロード
sys::preference& pre = director_.at().preference_;
if(menu_ != nullptr) {
menu_->load(pre, false, false);
}
/// project_.load(pre);
if(terminal_frame_ != nullptr) {
terminal_frame_->load(pre);
}
if(view_frame_ != nullptr) {
view_frame_->load(pre);
}
// if(argv_frame_ != nullptr) {
// argv_frame_->load(pre);
// }
if(load_ctx_ != nullptr) load_ctx_->load(pre);
/// if(save_ctx_ != nullptr) save_ctx_->load(pre);
/// if(edit_ != nullptr) edit_->load(pre);
// テスト・サーバー起動
server_.start();
// テスト波形生成
waves_.create_waves(0.5, 5.0 * 10e-6);
waves_.create_sin(1000, 5 * 10e-6);
}
//-----------------------------------------------------------------//
/*!
@brief アップデート
*/
//-----------------------------------------------------------------//
void update()
{
if(start_client_) {
client_.service();
} else {
client_.start();
start_client_ = true;
}
server_.service();
io_service_.run();
gui::widget_director& wd = director_.at().widget_director_;
#if 0
// Drag & Drop されたファイル
gl::core& core = gl::core::get_instance();
int id = core.get_recv_files_id();
if(drop_file_id_ != id) {
drop_file_id_ = id;
const utils::strings& ss = core.get_recv_files_path();
if(!ss.empty()) {
std::string path = ss[0];
if(load_ctx_ != nullptr && load_ctx_->get_local_param().select_file_func_ != nullptr) {
load_ctx_->get_local_param().select_file_func_(path);
}
}
}
#endif
wd.update();
}
//-----------------------------------------------------------------//
/*!
@brief レンダリング
*/
//-----------------------------------------------------------------//
void render()
{
director_.at().widget_director_.service();
director_.at().widget_director_.render();
}
//-----------------------------------------------------------------//
/*!
@brief 廃棄
*/
//-----------------------------------------------------------------//
void destroy()
{
sys::preference& pre = director_.at().preference_;
/// if(edit_ != nullptr) edit_->save(pre);
if(load_ctx_ != nullptr) load_ctx_->save(pre);
/// if(save_ctx_ != nullptr) save_ctx_->save(pre);
// if(argv_frame_ != nullptr) {
// argv_frame_->save(pre);
// }
if(view_frame_ != nullptr) {
view_frame_->save(pre);
}
if(terminal_frame_ != nullptr) {
terminal_frame_->save(pre);
}
// project_.save(pre);
if(menu_ != nullptr) {
menu_->save(pre);
}
}
};
}
<|endoftext|> |
<commit_before>/*
* ScopeLink.cc
*
* Copyright (C) 2009, 2014, 2015 Linas Vepstas
*
* Author: Linas Vepstas <[email protected]> January 2009
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the
* exceptions at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string>
#include <opencog/util/mt19937ar.h>
#include <opencog/util/Logger.h>
#include <opencog/atoms/base/ClassServer.h>
#include <opencog/atoms/core/LambdaLink.h>
#include <opencog/atoms/core/TypeNode.h>
#include "ScopeLink.h"
using namespace opencog;
void ScopeLink::init(void)
{
extract_variables(_outgoing);
}
ScopeLink::ScopeLink(const Handle& vars, const Handle& body)
: Link(HandleSeq({vars, body}), SCOPE_LINK)
{
init();
}
bool ScopeLink::skip_init(Type t)
{
// Type must be as expected.
if (not classserver().isA(t, SCOPE_LINK))
{
const std::string& tname = classserver().getTypeName(t);
throw InvalidParamException(TRACE_INFO,
"Expecting a ScopeLink, got %s", tname.c_str());
}
// Certain derived classes want to have a different initialization
// sequence. We can't use virtual init() in the ctor, so just
// do an if-statement here.
if (IMPLICATION_SCOPE_LINK == t) return true;
if (PUT_LINK == t) return true;
if (classserver().isA(t, PATTERN_LINK)) return true;
return false;
}
ScopeLink::ScopeLink(Type t, const Handle& body)
: Link(HandleSeq({body}), t)
{
if (skip_init(t)) return;
init();
}
ScopeLink::ScopeLink(const HandleSeq& oset, Type t)
: Link(oset, t)
{
if (skip_init(t)) return;
init();
}
ScopeLink::ScopeLink(const Link &l)
: Link(l)
{
if (skip_init(l.get_type())) return;
init();
}
/* ================================================================= */
///
/// Find and unpack variable declarations, if any; otherwise, just
/// find all free variables.
///
void ScopeLink::extract_variables(const HandleSeq& oset)
{
if (oset.size() == 0)
throw SyntaxException(TRACE_INFO,
"Expecting a non-empty outgoing set.");
Type decls = oset.at(0)->get_type();
// If we trip over an unquote immediately, then we can assume that
// the whole link appears in some quote context. This cannot be
// treated as an ordinary ScopeLink in any way ... halt all further
// initialization now.
if (UNQUOTE_LINK == decls)
return;
// If the first atom is not explicitly a variable declaration, then
// there are no variable declarations. There are two cases that can
// apply here: either the body is a lambda, in which case, we copy
// the variables from the lambda; else we extract all free variables.
if (VARIABLE_LIST != decls and
// A VariableNode could a be valid body, if it has no variable
// declaration, that is if the Scope has only one argument.
(VARIABLE_NODE != decls or oset.size() == 1) and
TYPED_VARIABLE_LINK != decls and
GLOB_NODE != decls)
{
_body = oset[0];
if (classserver().isA(_body->get_type(), LAMBDA_LINK))
{
LambdaLinkPtr lam(LambdaLinkCast(_body));
_varlist = lam->get_variables();
_body = lam->get_body();
}
else
{
_varlist.find_variables(oset[0]);
}
return;
}
if (oset.size() < 2)
throw SyntaxException(TRACE_INFO,
"Expecting an outgoing set size of at least two; got %s",
oset[0]->to_string().c_str());
// If we are here, then the first outgoing set member should be
// a variable declaration.
_vardecl = oset[0];
_body = oset[1];
// Initialize _varlist with the scoped variables
init_scoped_variables(_vardecl);
}
/* ================================================================= */
///
/// Initialize _varlist given a handle of either VariableList or a
/// variable.
///
void ScopeLink::init_scoped_variables(const Handle& hvar)
{
// Use the VariableList class as a tool to extract the variables
// for us.
VariableList vl(hvar);
_varlist = vl.get_variables();
}
/* ================================================================= */
///
/// Compare other ScopeLink, return true if it is equal to this one,
/// up to an alpha-conversion of variables.
///
bool ScopeLink::is_equal(const Handle& other, bool silent) const
{
if (other == this) return true;
if (other->get_type() != _type) return false;
ScopeLinkPtr scother(ScopeLinkCast(other));
// If the hashes are not equal, they can't possibly be equivalent.
if (get_hash() != scother->get_hash()) return false;
// Some derived classes (such as BindLink) have multiple body parts,
// so it is not enough to compare this->_body to other->_body.
// They tricky bit, below, is skipping over variable decls correctly,
// to find the remaining body parts. Start by counting to make sure
// that this and other have the same number of body parts.
Arity vardecl_offset = _vardecl != Handle::UNDEFINED;
Arity other_vardecl_offset = scother->_vardecl != Handle::UNDEFINED;
Arity n_scoped_terms = get_arity() - vardecl_offset;
Arity other_n_scoped_terms = other->get_arity() - other_vardecl_offset;
if (n_scoped_terms != other_n_scoped_terms) return false;
// Variable declarations must match.
if (not _varlist.is_equal(scother->_varlist)) return false;
// If all of the variable names are identical in this and other,
// then no alpha conversion needs to be done; we can do a direct
// comparison.
if (_varlist.is_identical(scother->_varlist))
{
// Compare them, they should match.
const HandleSeq& otho(other->getOutgoingSet());
for (Arity i = 0; i < n_scoped_terms; ++i)
{
const Handle& h(_outgoing[i + vardecl_offset]);
const Handle& other_h(otho[i + other_vardecl_offset]);
if (h->operator!=(*((AtomPtr) other_h))) return false;
}
return true;
}
// If we are here, we need to perform alpha conversion to test
// equality. Other terms, with our variables in place of its
// variables, should be same as our terms.
for (Arity i = 0; i < n_scoped_terms; ++i)
{
Handle h = getOutgoingAtom(i + vardecl_offset);
Handle other_h = other->getOutgoingAtom(i + other_vardecl_offset);
other_h = scother->_varlist.substitute_nocheck(other_h,
_varlist.varseq, silent);
// Compare them, they should match.
if (*((AtomPtr)h) != *((AtomPtr) other_h)) return false;
}
return true;
}
/* ================================================================= */
/// A specialized hashing function, designed so that all alpha-
/// convertable links get exactly the same hash. To acheive this,
/// the actual variable names have to be excluded from the hash,
/// and a standardized set used instead.
//
// There's a lot of prime-numbers in the code below, but the
// actual mixing and avalanching is extremely poor. I'm hoping
// its good enough for hash buckets, but have not verified.
//
// (In the code below, the numbers of the form `((1UL<<35) - 325)`
// etc. are all prime numbers. "Mixing" refers to code having the
// form `hash += (hash<<5) + other_stuff;` -- the shift and add
// mixes the bits. "Avalanching" refers to single-bit differences
// rapidly turning into multi-bit differences.)
//
// There's also an issue that there are multiple places where the
// hash must not mix, and must stay abelian, in order to deal with
// unordered links and alpha-conversion. (Here, "abelian" refers to
// order independence; addition is abelian; while "mixing" as
// defined above, is non-abelian).
//
ContentHash ScopeLink::compute_hash() const
{
ContentHash hsh = ((1UL<<35) - 325) * get_type();
hsh += (hsh <<5) + ((1UL<<47) - 649) * _varlist.varseq.size();
// It is not safe to mix here, since the sort order of the
// typemaps will depend on the variable names. So must be
// abelian.
ContentHash vth = 0;
for (const auto& pr : _varlist._simple_typemap)
{
for (Type t : pr.second) vth += ((1UL<<19) - 87) * t;
}
for (const auto& pr : _varlist._deep_typemap)
{
for (const Handle& th : pr.second) vth += th->get_hash();
}
hsh += (hsh <<5) + (vth % ((1UL<<27) - 235));
Arity vardecl_offset = _vardecl != Handle::UNDEFINED;
Arity n_scoped_terms = get_arity() - vardecl_offset;
UnorderedHandleSet hidden;
for (Arity i = 0; i < n_scoped_terms; ++i)
{
const Handle& h(_outgoing[i + vardecl_offset]);
hsh += (hsh<<5) + term_hash(h, hidden);
}
hsh %= (1UL << 63) - 409;
// Links will always have the MSB set.
ContentHash mask = ((ContentHash) 1UL) << (8*sizeof(ContentHash) - 1);
hsh |= mask;
if (Handle::INVALID_HASH == hsh) hsh -= 1;
_content_hash = hsh;
return _content_hash;
}
/// Recursive helper for computing the content hash correctly for
/// scoped links. The algorithm here is almost identical to that
/// used in VarScraper::find_vars(), with obvious alterations.
ContentHash ScopeLink::term_hash(const Handle& h,
UnorderedHandleSet& bound_vars,
Quotation quotation) const
{
Type t = h->get_type();
if ((VARIABLE_NODE == t or GLOB_NODE == t) and
quotation.is_unquoted() and
0 != _varlist.varset.count(h) and
0 == bound_vars.count(h))
{
// Alpha-convert the variable "name" to its unique position
// in the sequence of bound vars. Thus, the name is unique.
return ((1UL<<24)-77) * (1 + _varlist.index.find(h)->second);
}
// Just the plain old hash for all other nodes.
if (h->is_node()) return h->get_hash();
// Quotation
quotation.update(t);
// Other embedded ScopeLinks might be hiding some of our variables...
bool issco = classserver().isA(t, SCOPE_LINK);
UnorderedHandleSet bsave;
if (issco)
{
// Protect current hidden vars from harm.
bsave = bound_vars;
// Add the Scope link vars to the hidden set.
ScopeLinkPtr sco(ScopeLinkCast(h));
const Variables& vees = sco->get_variables();
for (const Handle& v : vees.varseq) bound_vars.insert(v);
}
// Prevent mixing for UnorderedLinks. The `mixer` var will be zero
// for UnorderedLinks. The problem is that two UnorderdLinks might
// be alpha-equivalent, but have their atoms presented in a
// different order. Thus, the hash must be computed in a purely
// commutative fashion: using only addition, so as to never create
// any entropy, until the end.
//
// XXX As discussed in issue #1176, a better fix would be to
// compute the individual term_hashes first, then sort them,
// and then mix them! This provides the desired qualities:
// different unordered links can be directly compared, and also
// have good mixing/avalanching properties. The code below
// only allows for compare; it fails to mix.
//
bool is_ordered = not classserver().isA(t, UNORDERED_LINK);
ContentHash mixer = (ContentHash) is_ordered;
ContentHash hsh = ((1UL<<8) - 59) * t;
for (const Handle& ho: h->getOutgoingSet())
{
hsh += mixer * (hsh<<5) + term_hash(ho, bound_vars, quotation);
}
hsh %= (1UL<<63) - 471;
// Restore saved vars from stack.
if (issco) bound_vars = bsave;
return hsh;
}
/* ================================================================= */
inline std::string rand_hex_str()
{
int rnd_id = randGen().randint();
std::stringstream ss;
ss << std::hex << rnd_id;
return ss.str();
}
inline HandleSeq append_rand_str(const HandleSeq& vars)
{
HandleSeq new_vars;
for (const Handle& h : vars) {
std::string new_var_name = h->get_name() + "-" + rand_hex_str();
new_vars.emplace_back(createNode(VARIABLE_NODE, new_var_name));
}
return new_vars;
}
Handle ScopeLink::alpha_conversion(HandleSeq vars) const
{
// If hs is empty then generate new variable names
if (vars.empty())
vars = append_rand_str(_varlist.varseq);
// Perform alpha conversion
HandleSeq hs;
for (size_t i = 0; i < get_arity(); ++i)
hs.push_back(_varlist.substitute_nocheck(getOutgoingAtom(i), vars));
// Create the alpha converted scope link
return createLink(hs, get_type());
}
/* ================================================================= */
bool ScopeLink::operator==(const Atom& ac) const
{
Atom& a = (Atom&) ac; // cast away constness, for smart ptr.
try {
return is_equal(a.get_handle(), true);
} catch (const NestingException& ex) {}
return false;
}
bool ScopeLink::operator!=(const Atom& a) const
{
return not operator==(a);
}
DEFINE_LINK_FACTORY(ScopeLink, SCOPE_LINK);
/* ===================== END OF FILE ===================== */
<commit_msg>Use randstr from cogutil<commit_after>/*
* ScopeLink.cc
*
* Copyright (C) 2009, 2014, 2015 Linas Vepstas
*
* Author: Linas Vepstas <[email protected]> January 2009
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the
* exceptions at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string>
#include <opencog/util/mt19937ar.h>
#include <opencog/util/random.h>
#include <opencog/util/Logger.h>
#include <opencog/atoms/base/ClassServer.h>
#include <opencog/atoms/core/LambdaLink.h>
#include <opencog/atoms/core/TypeNode.h>
#include "ScopeLink.h"
using namespace opencog;
void ScopeLink::init(void)
{
extract_variables(_outgoing);
}
ScopeLink::ScopeLink(const Handle& vars, const Handle& body)
: Link(HandleSeq({vars, body}), SCOPE_LINK)
{
init();
}
bool ScopeLink::skip_init(Type t)
{
// Type must be as expected.
if (not classserver().isA(t, SCOPE_LINK))
{
const std::string& tname = classserver().getTypeName(t);
throw InvalidParamException(TRACE_INFO,
"Expecting a ScopeLink, got %s", tname.c_str());
}
// Certain derived classes want to have a different initialization
// sequence. We can't use virtual init() in the ctor, so just
// do an if-statement here.
if (IMPLICATION_SCOPE_LINK == t) return true;
if (PUT_LINK == t) return true;
if (classserver().isA(t, PATTERN_LINK)) return true;
return false;
}
ScopeLink::ScopeLink(Type t, const Handle& body)
: Link(HandleSeq({body}), t)
{
if (skip_init(t)) return;
init();
}
ScopeLink::ScopeLink(const HandleSeq& oset, Type t)
: Link(oset, t)
{
if (skip_init(t)) return;
init();
}
ScopeLink::ScopeLink(const Link &l)
: Link(l)
{
if (skip_init(l.get_type())) return;
init();
}
/* ================================================================= */
///
/// Find and unpack variable declarations, if any; otherwise, just
/// find all free variables.
///
void ScopeLink::extract_variables(const HandleSeq& oset)
{
if (oset.size() == 0)
throw SyntaxException(TRACE_INFO,
"Expecting a non-empty outgoing set.");
Type decls = oset.at(0)->get_type();
// If we trip over an unquote immediately, then we can assume that
// the whole link appears in some quote context. This cannot be
// treated as an ordinary ScopeLink in any way ... halt all further
// initialization now.
if (UNQUOTE_LINK == decls)
return;
// If the first atom is not explicitly a variable declaration, then
// there are no variable declarations. There are two cases that can
// apply here: either the body is a lambda, in which case, we copy
// the variables from the lambda; else we extract all free variables.
if (VARIABLE_LIST != decls and
// A VariableNode could a be valid body, if it has no variable
// declaration, that is if the Scope has only one argument.
(VARIABLE_NODE != decls or oset.size() == 1) and
TYPED_VARIABLE_LINK != decls and
GLOB_NODE != decls)
{
_body = oset[0];
if (classserver().isA(_body->get_type(), LAMBDA_LINK))
{
LambdaLinkPtr lam(LambdaLinkCast(_body));
_varlist = lam->get_variables();
_body = lam->get_body();
}
else
{
_varlist.find_variables(oset[0]);
}
return;
}
if (oset.size() < 2)
throw SyntaxException(TRACE_INFO,
"Expecting an outgoing set size of at least two; got %s",
oset[0]->to_string().c_str());
// If we are here, then the first outgoing set member should be
// a variable declaration.
_vardecl = oset[0];
_body = oset[1];
// Initialize _varlist with the scoped variables
init_scoped_variables(_vardecl);
}
/* ================================================================= */
///
/// Initialize _varlist given a handle of either VariableList or a
/// variable.
///
void ScopeLink::init_scoped_variables(const Handle& hvar)
{
// Use the VariableList class as a tool to extract the variables
// for us.
VariableList vl(hvar);
_varlist = vl.get_variables();
}
/* ================================================================= */
///
/// Compare other ScopeLink, return true if it is equal to this one,
/// up to an alpha-conversion of variables.
///
bool ScopeLink::is_equal(const Handle& other, bool silent) const
{
if (other == this) return true;
if (other->get_type() != _type) return false;
ScopeLinkPtr scother(ScopeLinkCast(other));
// If the hashes are not equal, they can't possibly be equivalent.
if (get_hash() != scother->get_hash()) return false;
// Some derived classes (such as BindLink) have multiple body parts,
// so it is not enough to compare this->_body to other->_body.
// They tricky bit, below, is skipping over variable decls correctly,
// to find the remaining body parts. Start by counting to make sure
// that this and other have the same number of body parts.
Arity vardecl_offset = _vardecl != Handle::UNDEFINED;
Arity other_vardecl_offset = scother->_vardecl != Handle::UNDEFINED;
Arity n_scoped_terms = get_arity() - vardecl_offset;
Arity other_n_scoped_terms = other->get_arity() - other_vardecl_offset;
if (n_scoped_terms != other_n_scoped_terms) return false;
// Variable declarations must match.
if (not _varlist.is_equal(scother->_varlist)) return false;
// If all of the variable names are identical in this and other,
// then no alpha conversion needs to be done; we can do a direct
// comparison.
if (_varlist.is_identical(scother->_varlist))
{
// Compare them, they should match.
const HandleSeq& otho(other->getOutgoingSet());
for (Arity i = 0; i < n_scoped_terms; ++i)
{
const Handle& h(_outgoing[i + vardecl_offset]);
const Handle& other_h(otho[i + other_vardecl_offset]);
if (h->operator!=(*((AtomPtr) other_h))) return false;
}
return true;
}
// If we are here, we need to perform alpha conversion to test
// equality. Other terms, with our variables in place of its
// variables, should be same as our terms.
for (Arity i = 0; i < n_scoped_terms; ++i)
{
Handle h = getOutgoingAtom(i + vardecl_offset);
Handle other_h = other->getOutgoingAtom(i + other_vardecl_offset);
other_h = scother->_varlist.substitute_nocheck(other_h,
_varlist.varseq, silent);
// Compare them, they should match.
if (*((AtomPtr)h) != *((AtomPtr) other_h)) return false;
}
return true;
}
/* ================================================================= */
/// A specialized hashing function, designed so that all alpha-
/// convertable links get exactly the same hash. To acheive this,
/// the actual variable names have to be excluded from the hash,
/// and a standardized set used instead.
//
// There's a lot of prime-numbers in the code below, but the
// actual mixing and avalanching is extremely poor. I'm hoping
// its good enough for hash buckets, but have not verified.
//
// (In the code below, the numbers of the form `((1UL<<35) - 325)`
// etc. are all prime numbers. "Mixing" refers to code having the
// form `hash += (hash<<5) + other_stuff;` -- the shift and add
// mixes the bits. "Avalanching" refers to single-bit differences
// rapidly turning into multi-bit differences.)
//
// There's also an issue that there are multiple places where the
// hash must not mix, and must stay abelian, in order to deal with
// unordered links and alpha-conversion. (Here, "abelian" refers to
// order independence; addition is abelian; while "mixing" as
// defined above, is non-abelian).
//
ContentHash ScopeLink::compute_hash() const
{
ContentHash hsh = ((1UL<<35) - 325) * get_type();
hsh += (hsh <<5) + ((1UL<<47) - 649) * _varlist.varseq.size();
// It is not safe to mix here, since the sort order of the
// typemaps will depend on the variable names. So must be
// abelian.
ContentHash vth = 0;
for (const auto& pr : _varlist._simple_typemap)
{
for (Type t : pr.second) vth += ((1UL<<19) - 87) * t;
}
for (const auto& pr : _varlist._deep_typemap)
{
for (const Handle& th : pr.second) vth += th->get_hash();
}
hsh += (hsh <<5) + (vth % ((1UL<<27) - 235));
Arity vardecl_offset = _vardecl != Handle::UNDEFINED;
Arity n_scoped_terms = get_arity() - vardecl_offset;
UnorderedHandleSet hidden;
for (Arity i = 0; i < n_scoped_terms; ++i)
{
const Handle& h(_outgoing[i + vardecl_offset]);
hsh += (hsh<<5) + term_hash(h, hidden);
}
hsh %= (1UL << 63) - 409;
// Links will always have the MSB set.
ContentHash mask = ((ContentHash) 1UL) << (8*sizeof(ContentHash) - 1);
hsh |= mask;
if (Handle::INVALID_HASH == hsh) hsh -= 1;
_content_hash = hsh;
return _content_hash;
}
/// Recursive helper for computing the content hash correctly for
/// scoped links. The algorithm here is almost identical to that
/// used in VarScraper::find_vars(), with obvious alterations.
ContentHash ScopeLink::term_hash(const Handle& h,
UnorderedHandleSet& bound_vars,
Quotation quotation) const
{
Type t = h->get_type();
if ((VARIABLE_NODE == t or GLOB_NODE == t) and
quotation.is_unquoted() and
0 != _varlist.varset.count(h) and
0 == bound_vars.count(h))
{
// Alpha-convert the variable "name" to its unique position
// in the sequence of bound vars. Thus, the name is unique.
return ((1UL<<24)-77) * (1 + _varlist.index.find(h)->second);
}
// Just the plain old hash for all other nodes.
if (h->is_node()) return h->get_hash();
// Quotation
quotation.update(t);
// Other embedded ScopeLinks might be hiding some of our variables...
bool issco = classserver().isA(t, SCOPE_LINK);
UnorderedHandleSet bsave;
if (issco)
{
// Protect current hidden vars from harm.
bsave = bound_vars;
// Add the Scope link vars to the hidden set.
ScopeLinkPtr sco(ScopeLinkCast(h));
const Variables& vees = sco->get_variables();
for (const Handle& v : vees.varseq) bound_vars.insert(v);
}
// Prevent mixing for UnorderedLinks. The `mixer` var will be zero
// for UnorderedLinks. The problem is that two UnorderdLinks might
// be alpha-equivalent, but have their atoms presented in a
// different order. Thus, the hash must be computed in a purely
// commutative fashion: using only addition, so as to never create
// any entropy, until the end.
//
// XXX As discussed in issue #1176, a better fix would be to
// compute the individual term_hashes first, then sort them,
// and then mix them! This provides the desired qualities:
// different unordered links can be directly compared, and also
// have good mixing/avalanching properties. The code below
// only allows for compare; it fails to mix.
//
bool is_ordered = not classserver().isA(t, UNORDERED_LINK);
ContentHash mixer = (ContentHash) is_ordered;
ContentHash hsh = ((1UL<<8) - 59) * t;
for (const Handle& ho: h->getOutgoingSet())
{
hsh += mixer * (hsh<<5) + term_hash(ho, bound_vars, quotation);
}
hsh %= (1UL<<63) - 471;
// Restore saved vars from stack.
if (issco) bound_vars = bsave;
return hsh;
}
/* ================================================================= */
inline HandleSeq append_rand_str(const HandleSeq& vars)
{
HandleSeq new_vars;
for (const Handle& h : vars) {
std::string new_var_name = randstr(h->get_name() + "-");
new_vars.emplace_back(createNode(VARIABLE_NODE, new_var_name));
}
return new_vars;
}
Handle ScopeLink::alpha_conversion(HandleSeq vars) const
{
// If hs is empty then generate new variable names
if (vars.empty())
vars = append_rand_str(_varlist.varseq);
// Perform alpha conversion
HandleSeq hs;
for (size_t i = 0; i < get_arity(); ++i)
hs.push_back(_varlist.substitute_nocheck(getOutgoingAtom(i), vars));
// Create the alpha converted scope link
return createLink(hs, get_type());
}
/* ================================================================= */
bool ScopeLink::operator==(const Atom& ac) const
{
Atom& a = (Atom&) ac; // cast away constness, for smart ptr.
try {
return is_equal(a.get_handle(), true);
} catch (const NestingException& ex) {}
return false;
}
bool ScopeLink::operator!=(const Atom& a) const
{
return not operator==(a);
}
DEFINE_LINK_FACTORY(ScopeLink, SCOPE_LINK);
/* ===================== END OF FILE ===================== */
<|endoftext|> |
<commit_before>// Function grapher: user can choose among a set of functions (e.g., sin() and
// log(), provide parameters for those functions and then graph them
#include "Simple_window.h"
#include "Graph.h"
int main()
try {
Point tl(400,150);
Fgraph_window fwin(tl,800,605,"Function Grapher");
return gui_main();
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
keep_window_open();
}
catch (...) {
cerr << "exception\n";
keep_window_open();
}<commit_msg>Complete header comment of Chapter 16, exercise 10<commit_after>// Chapter 16, exercise 10: function grapher: user can choose among a set of
// functions (e.g., sin() and log(), provide parameters for those functions and
// then graph them
#include "Simple_window.h"
#include "Graph.h"
int main()
try {
Point tl(400,150);
Fgraph_window fwin(tl,800,605,"Function Grapher");
return gui_main();
}
catch (exception& e) {
cerr << "exception: " << e.what() << endl;
keep_window_open();
}
catch (...) {
cerr << "exception\n";
keep_window_open();
}
<|endoftext|> |
<commit_before>#include <bits/stdc++.h>
using namespace std;
typedef vector <int> vi;
vector <string> piece;
vector <vector <int>> status;
int n = 8;
//int n;
int m = 8;
void rook(int row, int col){
status[row][col] = true;
for(int i=row+1; i<n; i++){
if(piece[i][col] != '0') break;
status[i][col] = true;
}
for(int i=row-1; i>=0; i--){
if(piece[i][col] != '0') break;
status[i][col] = true;
}
for(int i=col+1; i<m; i++){
if(piece[row][i] != '0') break;
status[row][i] = true;
}
for(int i=col-1; i>=0; i--){
if(piece[row][i] != '0') break;
status[row][i] = true;
}
return;
}
void knight(int row, int col){
status[row][col] = true;
if(row-2>=0 && col+1<m) status[row-2][col+1] = true;
if(row-1>=0 && col+2<m) status[row-1][col+2] = true;
if(row+1<n && col+2<m) status[row+1][col+2] = true;
if(row+2<n && col+1<m) status[row+2][col+1] = true;
if(row+2<n && col-1>=0) status[row+2][col-1] = true;
if(row+1<n && col-2>=0) status[row+1][col-2] = true;
if(row-1>=0 && col-2>=0) status[row-1][col-2] = true;
if(row-2>=0 && col-1 >= 0) status[row-2][col-1] = true;
return;
}
void king(int row, int col){
status[row][col] = true;
if(row-1>=0) status[row-1][col] = true;
if(row-1>=0 && col+1<m) status[row-1][col+1] = true;
if(col+1<m) status[row][col+1] = true;
if(row+1<n && col+1<m) status[row+1][col+1] = true;
if(row+1<n) status[row+1][col] = true;
if(row+1<n && col-1>=0) status[row+1][col-1] = true;
if(col-1>=0) status[row][col-1] = true;
if(row-1>=0 && col-1>=0) status[row-1][col-1] = true;
return;
}
void bishop(int row, int col){
status[row][col] = true;
for(int i=row+1; col-row+i<m && i<n; i++){
if(piece[i][col-row+i] != '0') break;
status[i][col-row+i] = true;
}
for(int i=row-1; col-row+i>=0 && i>=0; i--){
if(piece[i][col-row+i] != '0') break;
status[i][col-row+i] = true;
}
for(int i=row+1; col+row-i>=0 && i<n; i++){
if(piece[i][col+row-i] != '0') break;
status[i][col+row-i] = true;
}
for(int i=row-1; col+row-i<m && i>=0; i--){
if(piece[i][col+row-i] != '0') break;
status[i][col+row-i] = true;
}
return;
}
void queen(int row, int col){
bishop(row, col);
rook(row, col);
return;
}
void pawn(int row, int col, int color){
status[row][col] = true;
if(color == 0){
if(row+1<n && col-1>=0) status[row+1][col-1] = true;
if(row+1<n && col+1<m) status[row+1][col+1] = true;
}
else {
if(row-1>=0 && col+1<m) status[row-1][col+1] = true;
if(row-1>=0 && col-1<m) status[row-1][col-1] = true;
}
return;
}
void printv(ostream &cout){
for(int i=0; i<n; i++){
for(int j=0; j<m; j++) cout << piece[i][j];
cout << endl;
}
cout << endl;
}
void print(ostream &cout){
for(int i=0; i<n; i++){
for(int j=0; j<m; j++) cout << status[i][j];
cout << endl;
}
cout << endl;
}
int main(){
//ifstream cin("in.txt");
//ofstream cout("out.txt");
string a;
while(cin >> a){
//n = count(a.begin(), a.end(), '/') + 1;
//cout << n << endl;
piece.resize(n);
status.resize(n, vector <int> (m));
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
piece[i][j] = '0';
status[i][j] = false;
}
}
int index = 0;
int k = 0;
char current;
while(index != a.size()){
current = a[index];
if(current >= '1' && current <= '8') k+=current-'0'-1;
else if(current == '/') k--;
else piece[k/8][k%8] = current;
assert(k/8<n && k%8<m);
k++;
index++;
}
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
current = piece[i][j];
if(current == '0');
else if(tolower(current) == 'r') rook(i, j);
else if(tolower(current) == 'n') knight(i, j);
else if(tolower(current) == 'k') king(i, j);
else if(tolower(current) == 'q') queen(i, j);
else if(tolower(current) == 'b') bishop(i, j);
else if(current == 'p') pawn(i, j, 0);
else if(current == 'P') pawn(i, j, 1);
}
}
//print(cout);
//printv(cout);
int counter = 0;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(status[i][j] == false) counter++;
}
}
cout << counter << endl;
}
}
<commit_msg>Update chessboard_in_fen.cpp<commit_after>#include <bits/stdc++.h>
using namespace std;
typedef vector <int> vi;
vector <string> piece;
vector <vector <int>> status;
int n = 8;
//int n;
int m = 8;
void rook(int row, int col){
status[row][col] = true;
for(int i=row+1; i<n; i++){
if(piece[i][col] != '0') break;
status[i][col] = true;
}
for(int i=row-1; i>=0; i--){
if(piece[i][col] != '0') break;
status[i][col] = true;
}
for(int i=col+1; i<m; i++){
if(piece[row][i] != '0') break;
status[row][i] = true;
}
for(int i=col-1; i>=0; i--){
if(piece[row][i] != '0') break;
status[row][i] = true;
}
return;
}
void knight(int row, int col){
status[row][col] = true;
if(row-2>=0 && col+1<m) status[row-2][col+1] = true;
if(row-1>=0 && col+2<m) status[row-1][col+2] = true;
if(row+1<n && col+2<m) status[row+1][col+2] = true;
if(row+2<n && col+1<m) status[row+2][col+1] = true;
if(row+2<n && col-1>=0) status[row+2][col-1] = true;
if(row+1<n && col-2>=0) status[row+1][col-2] = true;
if(row-1>=0 && col-2>=0) status[row-1][col-2] = true;
if(row-2>=0 && col-1 >= 0) status[row-2][col-1] = true;
return;
}
void king(int row, int col){
status[row][col] = true;
if(row-1>=0) status[row-1][col] = true;
if(row-1>=0 && col+1<m) status[row-1][col+1] = true;
if(col+1<m) status[row][col+1] = true;
if(row+1<n && col+1<m) status[row+1][col+1] = true;
if(row+1<n) status[row+1][col] = true;
if(row+1<n && col-1>=0) status[row+1][col-1] = true;
if(col-1>=0) status[row][col-1] = true;
if(row-1>=0 && col-1>=0) status[row-1][col-1] = true;
return;
}
void bishop(int row, int col){
status[row][col] = true;
for(int i=row+1; col-row+i<m && i<n; i++){
if(piece[i][col-row+i] != '0') break;
status[i][col-row+i] = true;
}
for(int i=row-1; col-row+i>=0 && i>=0; i--){
if(piece[i][col-row+i] != '0') break;
status[i][col-row+i] = true;
}
for(int i=row+1; col+row-i>=0 && i<n; i++){
if(piece[i][col+row-i] != '0') break;
status[i][col+row-i] = true;
}
for(int i=row-1; col+row-i<m && i>=0; i--){
if(piece[i][col+row-i] != '0') break;
status[i][col+row-i] = true;
}
return;
}
void queen(int row, int col){
bishop(row, col);
rook(row, col);
return;
}
void pawn(int row, int col, int color){
status[row][col] = true;
if(color == 0){
if(row+1<n && col-1>=0) status[row+1][col-1] = true;
if(row+1<n && col+1<m) status[row+1][col+1] = true;
}
else {
if(row-1>=0 && col+1<m) status[row-1][col+1] = true;
if(row-1>=0 && col-1>=0) status[row-1][col-1] = true;
}
return;
}
void printv(ostream &cout){
for(int i=0; i<n; i++){
for(int j=0; j<m; j++) cout << piece[i][j];
cout << endl;
}
cout << endl;
}
void print(ostream &cout){
for(int i=0; i<n; i++){
for(int j=0; j<m; j++) cout << status[i][j];
cout << endl;
}
cout << endl;
}
int main(){
//ifstream cin("in.txt");
//ofstream cout("out.txt");
string a;
while(cin >> a){
//n = count(a.begin(), a.end(), '/') + 1;
//cout << n << endl;
piece.resize(n);
status.resize(n, vector <int> (m));
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
piece[i][j] = '0';
status[i][j] = false;
}
}
int index = 0;
int k = 0;
char current;
while(index != a.size()){
current = a[index];
if(current >= '1' && current <= '8') k+=current-'0'-1;
else if(current == '/') k--;
else piece[k/8][k%8] = current;
assert(k/8<n && k%8<m);
k++;
index++;
}
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
current = piece[i][j];
if(current == '0');
else if(tolower(current) == 'r') rook(i, j);
else if(tolower(current) == 'n') knight(i, j);
else if(tolower(current) == 'k') king(i, j);
else if(tolower(current) == 'q') queen(i, j);
else if(tolower(current) == 'b') bishop(i, j);
else if(current == 'p') pawn(i, j, 0);
else if(current == 'P') pawn(i, j, 1);
}
}
//print(cout);
//printv(cout);
int counter = 0;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(status[i][j] == false) counter++;
}
}
cout << counter << endl;
}
}
<|endoftext|> |
<commit_before>/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <core/CHIPCore.h>
#include <ChipShellCollection.h>
#if CONFIG_DEVICE_LAYER
#include <platform/CHIPDeviceLayer.h>
#endif
#if CHIP_ENABLE_OPENTHREAD
#include <stdio.h>
#include <lib/shell/Engine.h>
#include <lib/support/CHIPArgParser.hpp>
#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <platform/ThreadStackManager.h>
#if CHIP_TARGET_STYLE_EMBEDDED
#include <openthread/cli.h>
#include <openthread/instance.h>
#include <openthread/ip6.h>
#include <openthread/link.h>
#include <openthread/thread.h>
#else
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
using namespace chip;
using namespace chip::Shell;
using namespace chip::Platform;
using namespace chip::DeviceLayer;
using namespace chip::Logging;
using namespace chip::ArgParser;
static chip::Shell::Engine sShellOtcliSubcommands;
int cmd_otcli_help_iterator(shell_command_t * command, void * arg)
{
streamer_printf(streamer_get(), " %-15s %s\n\r", command->cmd_name, command->cmd_help);
return 0;
}
int cmd_otcli_help(int argc, char ** argv)
{
sShellOtcliSubcommands.ForEachCommand(cmd_otcli_help_iterator, nullptr);
return 0;
}
#if CHIP_TARGET_STYLE_EMBEDDED
int cmd_otcli_dispatch(int argc, char ** argv)
{
CHIP_ERROR error = CHIP_NO_ERROR;
// From OT CLI internal lib, kMaxLineLength = 128
#define kMaxLineLength 128
char buff[kMaxLineLength] = { 0 };
char * buff_ptr = buff;
int i = 0;
VerifyOrExit(argc > 0, error = CHIP_ERROR_INVALID_ARGUMENT);
for (i = 0; i < argc; i++)
{
size_t arg_len = strlen(argv[i]);
/* Make sure that the next argument won't overflow the buffer */
VerifyOrExit(buff_ptr + arg_len < buff + kMaxLineLength, error = CHIP_ERROR_BUFFER_TOO_SMALL);
strncpy(buff_ptr, argv[i], arg_len);
buff_ptr += arg_len;
/* Make sure that there is enough buffer for a space char */
if (buff_ptr + sizeof(char) < buff + kMaxLineLength)
{
strncpy(buff_ptr, " ", sizeof(char));
buff_ptr++;
}
}
buff_ptr = 0;
otCliConsoleInputLine(buff, buff_ptr - buff);
exit:
return error;
}
#elif CHIP_TARGET_STYLE_UNIX
int cmd_otcli_dispatch(int argc, char ** argv)
{
CHIP_ERROR error = CHIP_NO_ERROR;
int pid;
uid_t euid = geteuid();
char ctl_command[] = "/usr/local/sbin/ot-ctl";
// Must run as sudo.
if (euid != 0)
{
streamer_printf(streamer_get(), "Error otcli: requires running chip-shell as sudo\n\r");
error = CHIP_ERROR_INCORRECT_STATE;
ExitNow();
}
VerifyOrExit(argc > 0, error = CHIP_ERROR_INVALID_ARGUMENT);
// Fork and execute the command.
pid = fork();
VerifyOrExit(pid != -1, error = CHIP_ERROR_INCORRECT_STATE);
if (pid == 0)
{
// Child process to execute the command with provided arguments
--argv; // Restore access to entry [0] containing the command;
argv[0] = ctl_command;
if (execvp(ctl_command, argv) < 0)
{
streamer_printf(streamer_get(), "Error exec %s: %s\n", ctl_command, strerror(errno));
}
exit(errno);
}
else
{
// Parent process to wait on child.
int status;
wait(&status);
error = (status) ? CHIP_ERROR_INCORRECT_STATE : CHIP_NO_ERROR;
}
exit:
return error;
}
#endif // CHIP_TARGET_STYLE_UNIX
static const shell_command_t cmds_otcli_root = { &cmd_otcli_dispatch, "otcli", "Dispatch OpenThread CLI command" };
#if CHIP_TARGET_STYLE_EMBEDDED
static int OnOtCliOutput(const char * aBuf, uint16_t aBufLength, void * aContext)
{
return streamer_write(streamer_get(), aBuf, aBufLength);
}
#endif
#endif // CHIP_ENABLE_OPENTHREAD
void cmd_otcli_init()
{
#if CHIP_ENABLE_OPENTHREAD
#if CHIP_TARGET_STYLE_EMBEDDED
otCliConsoleInit(otInstanceInitSingle(), &OnOtCliOutput, NULL);
#endif
// Register the root otcli command with the top-level shell.
Engine::Root().RegisterCommands(&cmds_otcli_root, 1);
#endif // CHIP_ENABLE_OPENTHREAD
}
<commit_msg>Shell example: OT-CLI compilation error fixed for EFR32 boards. (#7275)<commit_after>/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <core/CHIPCore.h>
#include <ChipShellCollection.h>
#if CONFIG_DEVICE_LAYER
#include <platform/CHIPDeviceLayer.h>
#endif
#if CHIP_ENABLE_OPENTHREAD
#include <stdio.h>
#include <lib/shell/Engine.h>
#include <lib/support/CHIPArgParser.hpp>
#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <platform/ThreadStackManager.h>
#if CHIP_TARGET_STYLE_EMBEDDED
#include <openthread/cli.h>
#include <openthread/instance.h>
#include <openthread/ip6.h>
#include <openthread/link.h>
#include <openthread/thread.h>
#ifdef EFR32_OPENTHREAD_API
#ifndef SHELL_OTCLI_TX_BUFFER_SIZE
#define SHELL_OTCLI_TX_BUFFER_SIZE 1024
#endif
static char sTxBuffer[SHELL_OTCLI_TX_BUFFER_SIZE];
static constexpr uint16_t sTxLength = SHELL_OTCLI_TX_BUFFER_SIZE;
#endif
#else
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
using namespace chip;
using namespace chip::Shell;
using namespace chip::Platform;
using namespace chip::DeviceLayer;
using namespace chip::Logging;
using namespace chip::ArgParser;
static chip::Shell::Engine sShellOtcliSubcommands;
int cmd_otcli_help_iterator(shell_command_t * command, void * arg)
{
streamer_printf(streamer_get(), " %-15s %s\n\r", command->cmd_name, command->cmd_help);
return 0;
}
int cmd_otcli_help(int argc, char ** argv)
{
sShellOtcliSubcommands.ForEachCommand(cmd_otcli_help_iterator, nullptr);
return 0;
}
#if CHIP_TARGET_STYLE_EMBEDDED
int cmd_otcli_dispatch(int argc, char ** argv)
{
CHIP_ERROR error = CHIP_NO_ERROR;
// From OT CLI internal lib, kMaxLineLength = 128
#define kMaxLineLength 128
char buff[kMaxLineLength] = { 0 };
char * buff_ptr = buff;
int i = 0;
VerifyOrExit(argc > 0, error = CHIP_ERROR_INVALID_ARGUMENT);
for (i = 0; i < argc; i++)
{
size_t arg_len = strlen(argv[i]);
/* Make sure that the next argument won't overflow the buffer */
VerifyOrExit(buff_ptr + arg_len < buff + kMaxLineLength, error = CHIP_ERROR_BUFFER_TOO_SMALL);
strncpy(buff_ptr, argv[i], arg_len);
buff_ptr += arg_len;
/* Make sure that there is enough buffer for a space char */
if (buff_ptr + sizeof(char) < buff + kMaxLineLength)
{
strncpy(buff_ptr, " ", sizeof(char));
buff_ptr++;
}
}
buff_ptr = 0;
#ifdef EFR32_OPENTHREAD_API
otCliInputLine(buff);
#else
otCliConsoleInputLine(buff, buff_ptr - buff);
#endif
exit:
return error;
}
#elif CHIP_TARGET_STYLE_UNIX
int cmd_otcli_dispatch(int argc, char ** argv)
{
CHIP_ERROR error = CHIP_NO_ERROR;
int pid;
uid_t euid = geteuid();
char ctl_command[] = "/usr/local/sbin/ot-ctl";
// Must run as sudo.
if (euid != 0)
{
streamer_printf(streamer_get(), "Error otcli: requires running chip-shell as sudo\n\r");
error = CHIP_ERROR_INCORRECT_STATE;
ExitNow();
}
VerifyOrExit(argc > 0, error = CHIP_ERROR_INVALID_ARGUMENT);
// Fork and execute the command.
pid = fork();
VerifyOrExit(pid != -1, error = CHIP_ERROR_INCORRECT_STATE);
if (pid == 0)
{
// Child process to execute the command with provided arguments
--argv; // Restore access to entry [0] containing the command;
argv[0] = ctl_command;
if (execvp(ctl_command, argv) < 0)
{
streamer_printf(streamer_get(), "Error exec %s: %s\n", ctl_command, strerror(errno));
}
exit(errno);
}
else
{
// Parent process to wait on child.
int status;
wait(&status);
error = (status) ? CHIP_ERROR_INCORRECT_STATE : CHIP_NO_ERROR;
}
exit:
return error;
}
#endif // CHIP_TARGET_STYLE_UNIX
static const shell_command_t cmds_otcli_root = { &cmd_otcli_dispatch, "otcli", "Dispatch OpenThread CLI command" };
#if CHIP_TARGET_STYLE_EMBEDDED
#ifdef EFR32_OPENTHREAD_API
static int OnOtCliOutput(void * aContext, const char * aFormat, va_list aArguments)
{
int rval = vsnprintf(sTxBuffer, sTxLength, aFormat, aArguments);
VerifyOrExit(rval >= 0 && rval < sTxLength, rval = CHIP_ERROR_BUFFER_TOO_SMALL);
return streamer_write(streamer_get(), (const char *) sTxBuffer, rval);
exit:
return rval;
}
#else
static int OnOtCliOutput(const char * aBuf, uint16_t aBufLength, void * aContext)
{
return streamer_write(streamer_get(), aBuf, aBufLength);
}
#endif
#endif
#endif // CHIP_ENABLE_OPENTHREAD
void cmd_otcli_init()
{
#if CHIP_ENABLE_OPENTHREAD
#if CHIP_TARGET_STYLE_EMBEDDED
#ifdef EFR32_OPENTHREAD_API
otCliInit(otInstanceInitSingle(), &OnOtCliOutput, NULL);
#else
otCliConsoleInit(otInstanceInitSingle(), &OnOtCliOutput, NULL);
#endif
#endif
// Register the root otcli command with the top-level shell.
Engine::Root().RegisterCommands(&cmds_otcli_root, 1);
#endif // CHIP_ENABLE_OPENTHREAD
}
<|endoftext|> |
<commit_before>/*
* ScopeLink.cc
*
* Copyright (C) 2009, 2014, 2015 Linas Vepstas
*
* Author: Linas Vepstas <[email protected]> January 2009
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the
* exceptions at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string>
#include <opencog/util/mt19937ar.h>
#include <opencog/atoms/base/ClassServer.h>
#include <opencog/atoms/TypeNode.h>
#include <opencog/atoms/core/FreeLink.h>
#include <opencog/atoms/core/LambdaLink.h>
#include <opencog/atoms/core/PutLink.h>
#include <opencog/atoms/core/ImplicationLink.h>
#include <opencog/atoms/pattern/PatternLink.h>
#include <opencog/atomutils/TypeUtils.h>
#include "ScopeLink.h"
using namespace opencog;
void ScopeLink::init(void)
{
extract_variables(_outgoing);
}
ScopeLink::ScopeLink(const HandleSeq& oset,
TruthValuePtr tv, AttentionValuePtr av)
: Link(SCOPE_LINK, oset, tv, av)
{
init();
}
ScopeLink::ScopeLink(const Handle& vars, const Handle& body,
TruthValuePtr tv, AttentionValuePtr av)
: Link(SCOPE_LINK, HandleSeq({vars, body}), tv, av)
{
init();
}
bool ScopeLink::skip_init(Type t)
{
// Type must be as expected.
if (not classserver().isA(t, SCOPE_LINK))
{
const std::string& tname = classserver().getTypeName(t);
throw InvalidParamException(TRACE_INFO,
"Expecting a ScopeLink, got %s", tname.c_str());
}
// Certain derived classes want to have a different initialization
// sequence. We can't use virtual init() in the ctor, so just
// do an if-statement here.
if (IMPLICATION_LINK == t) return true;
if (PUT_LINK == t) return true;
if (classserver().isA(t, PATTERN_LINK)) return true;
return false;
}
ScopeLink::ScopeLink(Type t, const Handle& body,
TruthValuePtr tv, AttentionValuePtr av)
: Link(t, HandleSeq({body}), tv, av)
{
if (skip_init(t)) return;
init();
}
ScopeLink::ScopeLink(Type t, const HandleSeq& oset,
TruthValuePtr tv, AttentionValuePtr av)
: Link(t, oset, tv, av)
{
if (skip_init(t)) return;
init();
}
ScopeLink::ScopeLink(Link &l)
: Link(l)
{
if (skip_init(l.getType())) return;
init();
}
/* ================================================================= */
///
/// Find and unpack variable declarations, if any; otherwise, just
/// find all free variables.
///
void ScopeLink::extract_variables(const HandleSeq& oset)
{
if (oset.size() == 0)
throw SyntaxException(TRACE_INFO,
"Expecting a non-empty outgoing set.");
Type decls = oset.at(0)->getType();
// If the first atom is not explicitly a variable declaration, then
// there are no variable declarations. There are two cases that; can
// apply here: either the body is a lambda, in which case, we copy
// the variables from the lambda; else we extract all free variables.
if (VARIABLE_LIST != decls and
VARIABLE_NODE != decls and
TYPED_VARIABLE_LINK != decls and
GLOB_NODE != decls)
{
_body = oset[0];
if (classserver().isA(_body->getType(), LAMBDA_LINK))
{
LambdaLinkPtr lam(LambdaLinkCast(_body));
if (nullptr == lam)
lam = createLambdaLink(*LinkCast(_body));
_varlist = lam->get_variables();
_body = lam->get_body();
}
else
{
_varlist.find_variables(oset[0]);
}
return;
}
if (oset.size() < 2)
throw SyntaxException(TRACE_INFO,
"Expecting an outgoing set size of at least two; got %s",
oset[0]->toString().c_str());
// If we are here, then the first outgoing set member should be
// a variable declaration.
_vardecl = oset[0];
_body = oset[1];
// Initialize _varlist with the scoped variables
init_scoped_variables(_vardecl);
}
/* ================================================================= */
///
/// Initialize _varlist given a handle of either VariableList or a
/// variable.
///
void ScopeLink::init_scoped_variables(const Handle& hvar)
{
// Use the VariableList class as a tool to extract the variables
// for us.
VariableList vl(hvar);
_varlist = vl.get_variables();
}
/* ================================================================= */
///
/// Compare other ScopeLink, return true if it is equal to this one,
/// up to an alpha-conversion of variables.
///
bool ScopeLink::is_equal(const Handle& other, bool silent) const
{
if (other == this) return true;
if (other->getType() != _type) return false;
ScopeLinkPtr scother(ScopeLinkCast(other));
if (nullptr == scother)
scother = createScopeLink(*LinkCast(other));
// In case we're dealing with a class inheriting from ScopeLink,
// like BindLink, that has more than one scoped term, like
// implicand, etc, then we need to check the alpha equivalence
// over all terms. Before that, let's check that they have the
// same number of terms.
Arity vardecl_offset = _vardecl != Handle::UNDEFINED;
Arity other_vardecl_offset = scother->_vardecl != Handle::UNDEFINED;
Arity n_scoped_terms = getArity() - vardecl_offset;
Arity other_n_scoped_terms = other->getArity() - other_vardecl_offset;
if (n_scoped_terms != other_n_scoped_terms) return false;
// Variable declarations must match.
if (not _varlist.is_equal(scother->_varlist)) return false;
// If all of the variable names are identical in this and other,
// then no alpha conversion needs to be done; we can do a direct
// comparison.
if (_varlist.is_identical(scother->_varlist))
{
// Compare them, they should match.
for (Arity i = 0; i < n_scoped_terms; ++i)
{
Handle h = getOutgoingAtom(i + vardecl_offset);
Handle other_h = other->getOutgoingAtom(i + other_vardecl_offset);
if (*((AtomPtr)h) != *((AtomPtr) other_h)) return false;
}
return true;
}
// If we are here, we need to perform alpha conversion to test
// equality. Other terms, with our variables in place of its
// variables, should be same as our terms.
for (Arity i = 0; i < n_scoped_terms; ++i)
{
Handle h = getOutgoingAtom(i + vardecl_offset);
Handle other_h = other->getOutgoingAtom(i + other_vardecl_offset);
other_h = scother->_varlist.substitute_nocheck(other_h,
_varlist.varseq, silent);
// Compare them, they should match.
if (*((AtomPtr)h) != *((AtomPtr) other_h)) return false;
}
return true;
}
/* ================================================================= */
/// A specialized hashing function, designed so that all alpha-
/// convertable links get exactly the same hash. To acheive this
/// the actual variable names have to be excluded from the hash,
/// and a standardized set used instead.
///
ContentHash ScopeLink::compute_hash() const
{
UnorderedHandleSet hidden;
// djb hash
ContentHash hsh = 5381;
hsh += (hsh <<5) + getType();
for (const Handle& h: _outgoing)
{
hsh += (hsh <<5) + term_hash(h, hidden, 0); // recursive!
}
// Links will always have the MSB set.
ContentHash mask = ((ContentHash) 1UL) << (8*sizeof(ContentHash) - 1);
hsh |= mask;
if (Handle::INVALID_HASH == hsh) hsh -= 1;
_content_hash = hsh;
return _content_hash;
}
/// Recursive helper for computing the content hash correctly for
/// scoped links. The algorithm here is almost identical to that
/// used in VarScraper::find_vars(), with obvious alterations.
ContentHash ScopeLink::term_hash(const Handle& h,
UnorderedHandleSet& bound_vars,
int quote_lvl) const
{
Type t = h->getType();
if ((VARIABLE_NODE == t or GLOB_NODE == t) and
0 == quote_lvl and
0 != _varlist.varset.count(h) and
0 == bound_vars.count(h))
{
// Alpha-convert the variable "name" to its unique position
// in the sequence of bound vars. Thus, the name is unique.
return 11 + _varlist.index.find(h)->second;
}
// Just the plain old hash for all other nodes.
if (h->isNode()) return h->get_hash();
// quotation
if (QUOTE_LINK == t) quote_lvl++;
else if (UNQUOTE_LINK == t) quote_lvl--;
// Other embedded ScopeLinks might be hiding some of our varialbes...
bool issco = classserver().isA(t, SCOPE_LINK);
UnorderedHandleSet bsave;
if (issco)
{
// Prevent current hidden vars from harm.
bsave = bound_vars;
// Add the Scope links vars to the hidden set.
ScopeLinkPtr sco(ScopeLinkCast(h));
if (nullptr == sco)
sco = ScopeLink::factory(t, h->getOutgoingSet());
const Variables& vees = sco->get_variables();
for (const Handle& v : vees.varseq) bound_vars.insert(v);
}
// djb hash
ContentHash hsh = 5381;
hsh += (hsh <<5) + t;
for (const Handle& ho: h->getOutgoingSet())
{
hsh += (hsh <<5) + term_hash(ho, bound_vars, quote_lvl); // recursive!
}
// Links will always have the MSB set.
ContentHash mask = ((ContentHash) 1UL) << (8*sizeof(ContentHash) - 1);
hsh |= mask;
if (Handle::INVALID_HASH == hsh) hsh -= 1;
_content_hash = hsh;
// Restore save vars from stack.
if (issco) bound_vars = bsave;
return _content_hash;
}
/* ================================================================= */
inline std::string rand_hex_str()
{
int rnd_id = randGen().randint();
std::stringstream ss;
ss << std::hex << rnd_id;
return ss.str();
}
inline HandleSeq append_rand_str(const HandleSeq& vars)
{
HandleSeq new_vars;
for (const Handle& h : vars) {
std::string new_var_name = h->getName() + "-" + rand_hex_str();
new_vars.emplace_back(createNode(VARIABLE_NODE, new_var_name));
}
return new_vars;
}
Handle ScopeLink::alpha_conversion(HandleSeq vars, Handle vardecl) const
{
// If hs is empty then generate new variable names
if (vars.empty())
vars = append_rand_str(_varlist.varseq);
// Perform alpha conversion
HandleSeq hs;
for (size_t i = 0; i < getArity(); ++i)
hs.push_back(_varlist.substitute_nocheck(getOutgoingAtom(i), vars));
// Replace vardecl by the substituted version if any
if (vardecl.is_undefined() and _vardecl.is_defined())
vardecl = hs[0];
// Remove the optional variable declaration from hs
if (_vardecl.is_defined())
hs.erase(hs.begin());
// Filter vardecl
vardecl = filter_vardecl(vardecl, hs);
// Insert vardecl back in hs if defined
if (vardecl.is_defined())
hs.insert(hs.begin(), vardecl);
// Create the alpha converted scope link
return Handle(factory(getType(), hs));
}
/* ================================================================= */
bool ScopeLink::operator==(const Atom& ac) const
{
Atom& a = (Atom&) ac; // cast away constness, for smart ptr.
try {
return is_equal(a.getHandle(), true);
} catch (const NestingException& ex) {}
return false;
}
bool ScopeLink::operator!=(const Atom& a) const
{
return not operator==(a);
}
/* ================================================================= */
ScopeLinkPtr ScopeLink::factory(const Handle& h)
{
return factory(h->getType(), h->getOutgoingSet());
}
ScopeLinkPtr ScopeLink::factory(Type t, const HandleSeq& seq)
{
if (PUT_LINK == t)
return createPutLink(seq);
if (LAMBDA_LINK == t)
return createLambdaLink(seq);
if (classserver().isA(t, IMPLICATION_LINK))
return createImplicationLink(t, seq);
if (classserver().isA(t, PATTERN_LINK))
return PatternLink::factory(t, seq);
if (classserver().isA(t, SCOPE_LINK))
return createScopeLink(t, seq);
throw SyntaxException(TRACE_INFO,
"ScopeLink is not a factory for %s",
classserver().getTypeName(t).c_str());
}
/* ===================== END OF FILE ===================== */
<commit_msg>Remove cut-n-past cruft<commit_after>/*
* ScopeLink.cc
*
* Copyright (C) 2009, 2014, 2015 Linas Vepstas
*
* Author: Linas Vepstas <[email protected]> January 2009
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the
* exceptions at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string>
#include <opencog/util/mt19937ar.h>
#include <opencog/atoms/base/ClassServer.h>
#include <opencog/atoms/TypeNode.h>
#include <opencog/atoms/core/FreeLink.h>
#include <opencog/atoms/core/LambdaLink.h>
#include <opencog/atoms/core/PutLink.h>
#include <opencog/atoms/core/ImplicationLink.h>
#include <opencog/atoms/pattern/PatternLink.h>
#include <opencog/atomutils/TypeUtils.h>
#include "ScopeLink.h"
using namespace opencog;
void ScopeLink::init(void)
{
extract_variables(_outgoing);
}
ScopeLink::ScopeLink(const HandleSeq& oset,
TruthValuePtr tv, AttentionValuePtr av)
: Link(SCOPE_LINK, oset, tv, av)
{
init();
}
ScopeLink::ScopeLink(const Handle& vars, const Handle& body,
TruthValuePtr tv, AttentionValuePtr av)
: Link(SCOPE_LINK, HandleSeq({vars, body}), tv, av)
{
init();
}
bool ScopeLink::skip_init(Type t)
{
// Type must be as expected.
if (not classserver().isA(t, SCOPE_LINK))
{
const std::string& tname = classserver().getTypeName(t);
throw InvalidParamException(TRACE_INFO,
"Expecting a ScopeLink, got %s", tname.c_str());
}
// Certain derived classes want to have a different initialization
// sequence. We can't use virtual init() in the ctor, so just
// do an if-statement here.
if (IMPLICATION_LINK == t) return true;
if (PUT_LINK == t) return true;
if (classserver().isA(t, PATTERN_LINK)) return true;
return false;
}
ScopeLink::ScopeLink(Type t, const Handle& body,
TruthValuePtr tv, AttentionValuePtr av)
: Link(t, HandleSeq({body}), tv, av)
{
if (skip_init(t)) return;
init();
}
ScopeLink::ScopeLink(Type t, const HandleSeq& oset,
TruthValuePtr tv, AttentionValuePtr av)
: Link(t, oset, tv, av)
{
if (skip_init(t)) return;
init();
}
ScopeLink::ScopeLink(Link &l)
: Link(l)
{
if (skip_init(l.getType())) return;
init();
}
/* ================================================================= */
///
/// Find and unpack variable declarations, if any; otherwise, just
/// find all free variables.
///
void ScopeLink::extract_variables(const HandleSeq& oset)
{
if (oset.size() == 0)
throw SyntaxException(TRACE_INFO,
"Expecting a non-empty outgoing set.");
Type decls = oset.at(0)->getType();
// If the first atom is not explicitly a variable declaration, then
// there are no variable declarations. There are two cases that; can
// apply here: either the body is a lambda, in which case, we copy
// the variables from the lambda; else we extract all free variables.
if (VARIABLE_LIST != decls and
VARIABLE_NODE != decls and
TYPED_VARIABLE_LINK != decls and
GLOB_NODE != decls)
{
_body = oset[0];
if (classserver().isA(_body->getType(), LAMBDA_LINK))
{
LambdaLinkPtr lam(LambdaLinkCast(_body));
if (nullptr == lam)
lam = createLambdaLink(*LinkCast(_body));
_varlist = lam->get_variables();
_body = lam->get_body();
}
else
{
_varlist.find_variables(oset[0]);
}
return;
}
if (oset.size() < 2)
throw SyntaxException(TRACE_INFO,
"Expecting an outgoing set size of at least two; got %s",
oset[0]->toString().c_str());
// If we are here, then the first outgoing set member should be
// a variable declaration.
_vardecl = oset[0];
_body = oset[1];
// Initialize _varlist with the scoped variables
init_scoped_variables(_vardecl);
}
/* ================================================================= */
///
/// Initialize _varlist given a handle of either VariableList or a
/// variable.
///
void ScopeLink::init_scoped_variables(const Handle& hvar)
{
// Use the VariableList class as a tool to extract the variables
// for us.
VariableList vl(hvar);
_varlist = vl.get_variables();
}
/* ================================================================= */
///
/// Compare other ScopeLink, return true if it is equal to this one,
/// up to an alpha-conversion of variables.
///
bool ScopeLink::is_equal(const Handle& other, bool silent) const
{
if (other == this) return true;
if (other->getType() != _type) return false;
ScopeLinkPtr scother(ScopeLinkCast(other));
if (nullptr == scother)
scother = createScopeLink(*LinkCast(other));
// In case we're dealing with a class inheriting from ScopeLink,
// like BindLink, that has more than one scoped term, like
// implicand, etc, then we need to check the alpha equivalence
// over all terms. Before that, let's check that they have the
// same number of terms.
Arity vardecl_offset = _vardecl != Handle::UNDEFINED;
Arity other_vardecl_offset = scother->_vardecl != Handle::UNDEFINED;
Arity n_scoped_terms = getArity() - vardecl_offset;
Arity other_n_scoped_terms = other->getArity() - other_vardecl_offset;
if (n_scoped_terms != other_n_scoped_terms) return false;
// Variable declarations must match.
if (not _varlist.is_equal(scother->_varlist)) return false;
// If all of the variable names are identical in this and other,
// then no alpha conversion needs to be done; we can do a direct
// comparison.
if (_varlist.is_identical(scother->_varlist))
{
// Compare them, they should match.
for (Arity i = 0; i < n_scoped_terms; ++i)
{
Handle h = getOutgoingAtom(i + vardecl_offset);
Handle other_h = other->getOutgoingAtom(i + other_vardecl_offset);
if (*((AtomPtr)h) != *((AtomPtr) other_h)) return false;
}
return true;
}
// If we are here, we need to perform alpha conversion to test
// equality. Other terms, with our variables in place of its
// variables, should be same as our terms.
for (Arity i = 0; i < n_scoped_terms; ++i)
{
Handle h = getOutgoingAtom(i + vardecl_offset);
Handle other_h = other->getOutgoingAtom(i + other_vardecl_offset);
other_h = scother->_varlist.substitute_nocheck(other_h,
_varlist.varseq, silent);
// Compare them, they should match.
if (*((AtomPtr)h) != *((AtomPtr) other_h)) return false;
}
return true;
}
/* ================================================================= */
/// A specialized hashing function, designed so that all alpha-
/// convertable links get exactly the same hash. To acheive this
/// the actual variable names have to be excluded from the hash,
/// and a standardized set used instead.
///
ContentHash ScopeLink::compute_hash() const
{
UnorderedHandleSet hidden;
// djb hash
ContentHash hsh = 5381;
hsh += (hsh <<5) + getType();
for (const Handle& h: _outgoing)
{
hsh += (hsh <<5) + term_hash(h, hidden, 0); // recursive!
}
// Links will always have the MSB set.
ContentHash mask = ((ContentHash) 1UL) << (8*sizeof(ContentHash) - 1);
hsh |= mask;
if (Handle::INVALID_HASH == hsh) hsh -= 1;
_content_hash = hsh;
return _content_hash;
}
/// Recursive helper for computing the content hash correctly for
/// scoped links. The algorithm here is almost identical to that
/// used in VarScraper::find_vars(), with obvious alterations.
ContentHash ScopeLink::term_hash(const Handle& h,
UnorderedHandleSet& bound_vars,
int quote_lvl) const
{
Type t = h->getType();
if ((VARIABLE_NODE == t or GLOB_NODE == t) and
0 == quote_lvl and
0 != _varlist.varset.count(h) and
0 == bound_vars.count(h))
{
// Alpha-convert the variable "name" to its unique position
// in the sequence of bound vars. Thus, the name is unique.
return 11 + _varlist.index.find(h)->second;
}
// Just the plain old hash for all other nodes.
if (h->isNode()) return h->get_hash();
// quotation
if (QUOTE_LINK == t) quote_lvl++;
else if (UNQUOTE_LINK == t) quote_lvl--;
// Other embedded ScopeLinks might be hiding some of our varialbes...
bool issco = classserver().isA(t, SCOPE_LINK);
UnorderedHandleSet bsave;
if (issco)
{
// Prevent current hidden vars from harm.
bsave = bound_vars;
// Add the Scope links vars to the hidden set.
ScopeLinkPtr sco(ScopeLinkCast(h));
if (nullptr == sco)
sco = ScopeLink::factory(t, h->getOutgoingSet());
const Variables& vees = sco->get_variables();
for (const Handle& v : vees.varseq) bound_vars.insert(v);
}
// djb hash
ContentHash hsh = 5381;
hsh += (hsh <<5) + t;
for (const Handle& ho: h->getOutgoingSet())
{
hsh += (hsh <<5) + term_hash(ho, bound_vars, quote_lvl); // recursive!
}
// Restore saved vars from stack.
if (issco) bound_vars = bsave;
return hsh;
}
/* ================================================================= */
inline std::string rand_hex_str()
{
int rnd_id = randGen().randint();
std::stringstream ss;
ss << std::hex << rnd_id;
return ss.str();
}
inline HandleSeq append_rand_str(const HandleSeq& vars)
{
HandleSeq new_vars;
for (const Handle& h : vars) {
std::string new_var_name = h->getName() + "-" + rand_hex_str();
new_vars.emplace_back(createNode(VARIABLE_NODE, new_var_name));
}
return new_vars;
}
Handle ScopeLink::alpha_conversion(HandleSeq vars, Handle vardecl) const
{
// If hs is empty then generate new variable names
if (vars.empty())
vars = append_rand_str(_varlist.varseq);
// Perform alpha conversion
HandleSeq hs;
for (size_t i = 0; i < getArity(); ++i)
hs.push_back(_varlist.substitute_nocheck(getOutgoingAtom(i), vars));
// Replace vardecl by the substituted version if any
if (vardecl.is_undefined() and _vardecl.is_defined())
vardecl = hs[0];
// Remove the optional variable declaration from hs
if (_vardecl.is_defined())
hs.erase(hs.begin());
// Filter vardecl
vardecl = filter_vardecl(vardecl, hs);
// Insert vardecl back in hs if defined
if (vardecl.is_defined())
hs.insert(hs.begin(), vardecl);
// Create the alpha converted scope link
return Handle(factory(getType(), hs));
}
/* ================================================================= */
bool ScopeLink::operator==(const Atom& ac) const
{
Atom& a = (Atom&) ac; // cast away constness, for smart ptr.
try {
return is_equal(a.getHandle(), true);
} catch (const NestingException& ex) {}
return false;
}
bool ScopeLink::operator!=(const Atom& a) const
{
return not operator==(a);
}
/* ================================================================= */
ScopeLinkPtr ScopeLink::factory(const Handle& h)
{
return factory(h->getType(), h->getOutgoingSet());
}
ScopeLinkPtr ScopeLink::factory(Type t, const HandleSeq& seq)
{
if (PUT_LINK == t)
return createPutLink(seq);
if (LAMBDA_LINK == t)
return createLambdaLink(seq);
if (classserver().isA(t, IMPLICATION_LINK))
return createImplicationLink(t, seq);
if (classserver().isA(t, PATTERN_LINK))
return PatternLink::factory(t, seq);
if (classserver().isA(t, SCOPE_LINK))
return createScopeLink(t, seq);
throw SyntaxException(TRACE_INFO,
"ScopeLink is not a factory for %s",
classserver().getTypeName(t).c_str());
}
/* ===================== END OF FILE ===================== */
<|endoftext|> |
<commit_before>#ifndef __STOUT_OS_SYSCTL_HPP__
#define __STOUT_OS_SYSCTL_HPP__
// Only provide sysctl support for OS X.
#ifndef __APPLE__
#error "stout/os/sysctl.hpp is only available on OS X."
#endif
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <stout/error.hpp>
#include <stout/none.hpp>
#include <stout/option.hpp>
#include <stout/strings.hpp>
#include <stout/try.hpp>
namespace os {
// Provides an abstraction for getting system information via the
// underlying 'sysctl' system call. You describe the sysctl
// "Management Information Base" (MIB) name via the constructor, for
// example, to describe "maximum number of processes allowed in the
// system" you would do:
//
// os::sysctl(CTL_KERN, KERN_MAXPROC)
//
// To _retrieve_ the value you need to use one of the 'integer',
// 'string', or 'table' methods to indicate the type of the value
// being retrieved. For example:
//
// Try<int> maxproc = os::sysctl(CTL_KERN, KERN_MAXPROC).integer();
//
// Note that the 'table' method requires specifying a length. If you
// would like the length to be looked up dynamically you can just pass
// None. Here's an example using 'table' that builds on above:
//
// Try<vector<kinfo_proc> > processes =
// os::sysctl(CTL_KERN, KERN_PROC, KERN_PROC_ALL).table(maxprox.get());
//
// TODO(benh): Provide an 'integer(i)', 'string(s)', and 'table(t)' to
// enable setting system information.
struct sysctl
{
// Note that we create a constructor for each number of levels
// because we can't pick a suitable default for unused levels (in
// order to distinguish no value from some value) and while Option
// would solve that it could also cause people to use None which
// we'd need to later handle as an error.
explicit sysctl(int level1);
sysctl(int level1, int level2);
sysctl(int level1, int level2, int level3);
sysctl(int level1, int level2, int level3, int level4);
sysctl(int level1, int level2, int level3, int level4, int level5);
~sysctl();
// Get system information as an integer.
private: struct Integer; // Forward declaration.
public:
Integer integer() const;
// Get system information as a string.
Try<std::string> string() const;
// Get system information as a table, optionally specifying a
// length. Note that this function is lazy and will not actually
// perform the syscall until you cast (implicitely or explicitly) a
// 'Table' to a std::vector<T>. For example, to get the first 10
// processes in the process table you can do:
//
// Try<std::vector<kinfo_proc> > processes =
// os::sysctl(CTL_KERN, KERN_PROC, KERN_PROC_ALL).table(10);
//
private: struct Table; // Forward declaration.
public:
Table table(const Option<size_t>& length = None()) const;
private:
struct Integer
{
Integer(int _levels, int* _name);
template <typename T>
operator Try<T> ();
const int levels;
int* name;
};
struct Table
{
Table(int _levels, int* _name, const Option<size_t>& _length);
template <typename T>
operator Try<std::vector<T> > ();
const int levels;
int* name;
Option<size_t> length;
};
const int levels;
int* name;
};
inline sysctl::sysctl(int level1)
: levels(1), name(new int[levels])
{
name[0] = level1;
}
inline sysctl::sysctl(int level1, int level2)
: levels(2), name(new int[levels])
{
name[0] = level1;
name[1] = level2;
}
inline sysctl::sysctl(int level1, int level2, int level3)
: levels(3), name(new int[levels])
{
name[0] = level1;
name[1] = level2;
name[2] = level3;
}
inline sysctl::sysctl(int level1, int level2, int level3, int level4)
: levels(4), name(new int[levels])
{
name[0] = level1;
name[1] = level2;
name[2] = level3;
name[3] = level4;
}
inline sysctl::sysctl(int level1, int level2, int level3, int level4, int level5)
: levels(5), name(new int[levels])
{
name[0] = level1;
name[1] = level2;
name[2] = level3;
name[3] = level4;
name[4] = level5;
}
inline sysctl::~sysctl()
{
delete[] name;
}
inline sysctl::Integer sysctl::integer() const
{
return Integer(levels, name);
}
inline Try<std::string> sysctl::string() const
{
// First determine the size of the string.
size_t size = 0;
if (::sysctl(name, levels, NULL, &size, NULL, 0) == -1) {
return ErrnoError();
}
// Now read it.
size_t length = size / sizeof(char);
char* temp = new char[length];
if (::sysctl(name, levels, temp, &size, NULL, 0) == -1) {
Error error = ErrnoError();
delete[] temp;
return error;
}
// TODO(benh): It's possible that the value has changed since we
// determined it's length above. We should really check that we
// get back the same length and if not throw an error.
std::string result(temp);
delete[] temp;
return result;
}
inline sysctl::Table sysctl::table(const Option<size_t>& length) const
{
return Table(levels, name, length);
}
inline sysctl::Integer::Integer(
int _levels,
int* _name)
: levels(_levels),
name(_name)
{}
template <typename T>
sysctl::Integer::operator Try<T> ()
{
T i;
size_t size = sizeof(i);
if (::sysctl(name, levels, &i, &size, NULL, 0) == -1) {
return ErrnoError();
}
return i;
}
inline sysctl::Table::Table(
int _levels,
int* _name,
const Option<size_t>& _length)
: levels(_levels),
name(_name),
length(_length)
{}
template <typename T>
sysctl::Table::operator Try<std::vector<T> > ()
{
size_t size = 0;
if (length.isNone()) {
if (::sysctl(name, levels, NULL, &size, NULL, 0) == -1) {
return ErrnoError();
}
if (size % sizeof(T) != 0) {
return Error("Failed to determine the length of result, "
"amount of available data is not a multiple "
"of the table type");
}
length = Option<size_t>(size / sizeof(T));
}
T* ts = new T[length.get()];
size = length.get() * sizeof(T);
if (::sysctl(name, levels, ts, &size, NULL, 0) == -1) {
Error error = ErrnoError();
delete[] ts;
return error;
}
// TODO(benh): It's possible that the value has changed since we
// determined it's length above (or from what was specified). We
// should really check that we get back the same length and if not
// throw an error.
length = size / sizeof(T);
std::vector<T> results;
for (size_t i = 0; i < length.get(); i++) {
results.push_back(ts[i]);
}
delete[] ts;
return results;
}
} // namespace os {
#endif // __STOUT_OS_SYSCTL_HPP__
<commit_msg>Fixed os::sysctl::string to return results with null bytes.<commit_after>#ifndef __STOUT_OS_SYSCTL_HPP__
#define __STOUT_OS_SYSCTL_HPP__
// Only provide sysctl support for OS X.
#ifndef __APPLE__
#error "stout/os/sysctl.hpp is only available on OS X."
#endif
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <stout/error.hpp>
#include <stout/none.hpp>
#include <stout/option.hpp>
#include <stout/strings.hpp>
#include <stout/try.hpp>
namespace os {
// Provides an abstraction for getting system information via the
// underlying 'sysctl' system call. You describe the sysctl
// "Management Information Base" (MIB) name via the constructor, for
// example, to describe "maximum number of processes allowed in the
// system" you would do:
//
// os::sysctl(CTL_KERN, KERN_MAXPROC)
//
// To _retrieve_ the value you need to use one of the 'integer',
// 'string', or 'table' methods to indicate the type of the value
// being retrieved. For example:
//
// Try<int> maxproc = os::sysctl(CTL_KERN, KERN_MAXPROC).integer();
//
// Note that the 'table' method requires specifying a length. If you
// would like the length to be looked up dynamically you can just pass
// None. Here's an example using 'table' that builds on above:
//
// Try<vector<kinfo_proc> > processes =
// os::sysctl(CTL_KERN, KERN_PROC, KERN_PROC_ALL).table(maxprox.get());
//
// TODO(benh): Provide an 'integer(i)', 'string(s)', and 'table(t)' to
// enable setting system information.
struct sysctl
{
// Note that we create a constructor for each number of levels
// because we can't pick a suitable default for unused levels (in
// order to distinguish no value from some value) and while Option
// would solve that it could also cause people to use None which
// we'd need to later handle as an error.
explicit sysctl(int level1);
sysctl(int level1, int level2);
sysctl(int level1, int level2, int level3);
sysctl(int level1, int level2, int level3, int level4);
sysctl(int level1, int level2, int level3, int level4, int level5);
~sysctl();
// Get system information as an integer.
private: struct Integer; // Forward declaration.
public:
Integer integer() const;
// Get system information as a string.
Try<std::string> string() const;
// Get system information as a table, optionally specifying a
// length. Note that this function is lazy and will not actually
// perform the syscall until you cast (implicitely or explicitly) a
// 'Table' to a std::vector<T>. For example, to get the first 10
// processes in the process table you can do:
//
// Try<std::vector<kinfo_proc> > processes =
// os::sysctl(CTL_KERN, KERN_PROC, KERN_PROC_ALL).table(10);
//
private: struct Table; // Forward declaration.
public:
Table table(const Option<size_t>& length = None()) const;
private:
struct Integer
{
Integer(int _levels, int* _name);
template <typename T>
operator Try<T> ();
const int levels;
int* name;
};
struct Table
{
Table(int _levels, int* _name, const Option<size_t>& _length);
template <typename T>
operator Try<std::vector<T> > ();
const int levels;
int* name;
Option<size_t> length;
};
const int levels;
int* name;
};
inline sysctl::sysctl(int level1)
: levels(1), name(new int[levels])
{
name[0] = level1;
}
inline sysctl::sysctl(int level1, int level2)
: levels(2), name(new int[levels])
{
name[0] = level1;
name[1] = level2;
}
inline sysctl::sysctl(int level1, int level2, int level3)
: levels(3), name(new int[levels])
{
name[0] = level1;
name[1] = level2;
name[2] = level3;
}
inline sysctl::sysctl(int level1, int level2, int level3, int level4)
: levels(4), name(new int[levels])
{
name[0] = level1;
name[1] = level2;
name[2] = level3;
name[3] = level4;
}
inline sysctl::sysctl(int level1, int level2, int level3, int level4, int level5)
: levels(5), name(new int[levels])
{
name[0] = level1;
name[1] = level2;
name[2] = level3;
name[3] = level4;
name[4] = level5;
}
inline sysctl::~sysctl()
{
delete[] name;
}
inline sysctl::Integer sysctl::integer() const
{
return Integer(levels, name);
}
inline Try<std::string> sysctl::string() const
{
// First determine the size of the string.
size_t size = 0;
if (::sysctl(name, levels, NULL, &size, NULL, 0) == -1) {
return ErrnoError();
}
// Now read it.
size_t length = size / sizeof(char);
char* temp = new char[length];
if (::sysctl(name, levels, temp, &size, NULL, 0) == -1) {
Error error = ErrnoError();
delete[] temp;
return error;
}
// TODO(benh): It's possible that the value has changed since we
// determined it's length above. We should really check that we
// get back the same length and if not throw an error.
// The "string" in 'temp' might include null bytes, so to get all of
// the data we need to create a string with 'size' (but we exclude
// the last null byte via 'size - 1').
std::string result(temp, size - 1);
delete[] temp;
return result;
}
inline sysctl::Table sysctl::table(const Option<size_t>& length) const
{
return Table(levels, name, length);
}
inline sysctl::Integer::Integer(
int _levels,
int* _name)
: levels(_levels),
name(_name)
{}
template <typename T>
sysctl::Integer::operator Try<T> ()
{
T i;
size_t size = sizeof(i);
if (::sysctl(name, levels, &i, &size, NULL, 0) == -1) {
return ErrnoError();
}
return i;
}
inline sysctl::Table::Table(
int _levels,
int* _name,
const Option<size_t>& _length)
: levels(_levels),
name(_name),
length(_length)
{}
template <typename T>
sysctl::Table::operator Try<std::vector<T> > ()
{
size_t size = 0;
if (length.isNone()) {
if (::sysctl(name, levels, NULL, &size, NULL, 0) == -1) {
return ErrnoError();
}
if (size % sizeof(T) != 0) {
return Error("Failed to determine the length of result, "
"amount of available data is not a multiple "
"of the table type");
}
length = Option<size_t>(size / sizeof(T));
}
T* ts = new T[length.get()];
size = length.get() * sizeof(T);
if (::sysctl(name, levels, ts, &size, NULL, 0) == -1) {
Error error = ErrnoError();
delete[] ts;
return error;
}
// TODO(benh): It's possible that the value has changed since we
// determined it's length above (or from what was specified). We
// should really check that we get back the same length and if not
// throw an error.
length = size / sizeof(T);
std::vector<T> results;
for (size_t i = 0; i < length.get(); i++) {
results.push_back(ts[i]);
}
delete[] ts;
return results;
}
} // namespace os {
#endif // __STOUT_OS_SYSCTL_HPP__
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/system_wrappers/interface/condition_variable_wrapper.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/thread_wrapper.h"
#include "webrtc/system_wrappers/interface/trace.h"
namespace webrtc {
namespace {
const int kLongWaitMs = 100 * 1000; // A long time in testing terms
const int kShortWaitMs = 2 * 1000; // Long enough for process switches to happen
// A Baton is one possible control structure one can build using
// conditional variables.
// A Baton is always held by one and only one active thread - unlike
// a lock, it can never be free.
// One can pass it or grab it - both calls have timeouts.
// Note - a production tool would guard against passing it without
// grabbing it first. This one is for testing, so it doesn't.
class Baton {
public:
Baton()
: giver_sect_(CriticalSectionWrapper::CreateCriticalSection()),
crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
cond_var_(ConditionVariableWrapper::CreateConditionVariable()),
being_passed_(false),
pass_count_(0) {
}
~Baton() {
delete giver_sect_;
delete crit_sect_;
delete cond_var_;
}
// Pass the baton. Returns false if baton is not picked up in |max_msecs|.
// Only one process can pass at the same time; this property is
// ensured by the |giver_sect_| lock.
bool Pass(uint32_t max_msecs) {
CriticalSectionScoped cs_giver(giver_sect_);
CriticalSectionScoped cs(crit_sect_);
SignalBatonAvailable();
const bool result = TakeBatonIfStillFree(max_msecs);
if (result) {
++pass_count_;
}
return result;
}
// Grab the baton. Returns false if baton is not passed.
bool Grab(uint32_t max_msecs) {
CriticalSectionScoped cs(crit_sect_);
return WaitUntilBatonOffered(max_msecs);
}
int PassCount() {
// We don't allow polling PassCount() during a Pass()-call since there is
// no guarantee that |pass_count_| is incremented until the Pass()-call
// finishes. I.e. the Grab()-call may finish before |pass_count_| has been
// incremented.
// Thus, this function waits on giver_sect_.
CriticalSectionScoped cs(giver_sect_);
return pass_count_;
}
private:
// Wait/Signal forms a classical semaphore on |being_passed_|.
// These functions must be called with crit_sect_ held.
bool WaitUntilBatonOffered(int timeout_ms) {
while (!being_passed_) {
if (!cond_var_->SleepCS(*crit_sect_, timeout_ms)) {
return false;
}
}
being_passed_ = false;
cond_var_->Wake();
return true;
}
void SignalBatonAvailable() {
assert(!being_passed_);
being_passed_ = true;
cond_var_->Wake();
}
// Timeout extension: Wait for a limited time for someone else to
// take it, and take it if it's not taken.
// Returns true if resource is taken by someone else, false
// if it is taken back by the caller.
// This function must be called with both |giver_sect_| and
// |crit_sect_| held.
bool TakeBatonIfStillFree(int timeout_ms) {
bool not_timeout = true;
while (being_passed_ && not_timeout) {
not_timeout = cond_var_->SleepCS(*crit_sect_, timeout_ms);
// If we're woken up while variable is still held, we may have
// gotten a wakeup destined for a grabber thread.
// This situation is not treated specially here.
}
if (!being_passed_) {
return true;
} else {
assert(!not_timeout);
being_passed_ = false;
return false;
}
}
// Lock that ensures that there is only one thread in the active
// part of Pass() at a time.
// |giver_sect_| must always be acquired before |cond_var_|.
CriticalSectionWrapper* giver_sect_;
// Lock that protects |being_passed_|.
CriticalSectionWrapper* crit_sect_;
ConditionVariableWrapper* cond_var_;
bool being_passed_;
// Statistics information: Number of successfull passes.
int pass_count_;
};
// Function that waits on a Baton, and passes it right back.
// We expect these calls never to time out.
bool WaitingRunFunction(void* obj) {
Baton* the_baton = static_cast<Baton*> (obj);
EXPECT_TRUE(the_baton->Grab(kLongWaitMs));
EXPECT_TRUE(the_baton->Pass(kLongWaitMs));
return true;
}
class CondVarTest : public ::testing::Test {
public:
CondVarTest() {}
virtual void SetUp() {
thread_ = ThreadWrapper::CreateThread(&WaitingRunFunction,
&baton_);
unsigned int id = 42;
ASSERT_TRUE(thread_->Start(id));
}
virtual void TearDown() {
// We have to wake the thread in order to make it obey the stop order.
// But we don't know if the thread has completed the run function, so
// we don't know if it will exit before or after the Pass.
// Thus, we need to pin it down inside its Run function (between Grab
// and Pass).
ASSERT_TRUE(baton_.Pass(kShortWaitMs));
ASSERT_TRUE(baton_.Grab(kShortWaitMs));
ASSERT_TRUE(thread_->Stop());
delete thread_;
}
protected:
Baton baton_;
private:
ThreadWrapper* thread_;
};
// The SetUp and TearDown functions use condition variables.
// This test verifies those pieces in isolation.
TEST_F(CondVarTest, InitFunctionsWork) {
// All relevant asserts are in the SetUp and TearDown functions.
}
// This test verifies that one can use the baton multiple times.
TEST_F(CondVarTest, DISABLED_PassBatonMultipleTimes) {
const int kNumberOfRounds = 2;
for (int i = 0; i < kNumberOfRounds; ++i) {
ASSERT_TRUE(baton_.Pass(kShortWaitMs));
ASSERT_TRUE(baton_.Grab(kShortWaitMs));
}
EXPECT_EQ(2 * kNumberOfRounds, baton_.PassCount());
}
} // anonymous namespace
} // namespace webrtc
<commit_msg>Disable CondVarTest.InitFunctionsWork. The order of Sleep/Wake calls doesn't seem to be guaranteed, so this test is flaky.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/system_wrappers/interface/condition_variable_wrapper.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/thread_wrapper.h"
#include "webrtc/system_wrappers/interface/trace.h"
namespace webrtc {
namespace {
const int kLongWaitMs = 100 * 1000; // A long time in testing terms
const int kShortWaitMs = 2 * 1000; // Long enough for process switches to happen
// A Baton is one possible control structure one can build using
// conditional variables.
// A Baton is always held by one and only one active thread - unlike
// a lock, it can never be free.
// One can pass it or grab it - both calls have timeouts.
// Note - a production tool would guard against passing it without
// grabbing it first. This one is for testing, so it doesn't.
class Baton {
public:
Baton()
: giver_sect_(CriticalSectionWrapper::CreateCriticalSection()),
crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
cond_var_(ConditionVariableWrapper::CreateConditionVariable()),
being_passed_(false),
pass_count_(0) {
}
~Baton() {
delete giver_sect_;
delete crit_sect_;
delete cond_var_;
}
// Pass the baton. Returns false if baton is not picked up in |max_msecs|.
// Only one process can pass at the same time; this property is
// ensured by the |giver_sect_| lock.
bool Pass(uint32_t max_msecs) {
CriticalSectionScoped cs_giver(giver_sect_);
CriticalSectionScoped cs(crit_sect_);
SignalBatonAvailable();
const bool result = TakeBatonIfStillFree(max_msecs);
if (result) {
++pass_count_;
}
return result;
}
// Grab the baton. Returns false if baton is not passed.
bool Grab(uint32_t max_msecs) {
CriticalSectionScoped cs(crit_sect_);
return WaitUntilBatonOffered(max_msecs);
}
int PassCount() {
// We don't allow polling PassCount() during a Pass()-call since there is
// no guarantee that |pass_count_| is incremented until the Pass()-call
// finishes. I.e. the Grab()-call may finish before |pass_count_| has been
// incremented.
// Thus, this function waits on giver_sect_.
CriticalSectionScoped cs(giver_sect_);
return pass_count_;
}
private:
// Wait/Signal forms a classical semaphore on |being_passed_|.
// These functions must be called with crit_sect_ held.
bool WaitUntilBatonOffered(int timeout_ms) {
while (!being_passed_) {
if (!cond_var_->SleepCS(*crit_sect_, timeout_ms)) {
return false;
}
}
being_passed_ = false;
cond_var_->Wake();
return true;
}
void SignalBatonAvailable() {
assert(!being_passed_);
being_passed_ = true;
cond_var_->Wake();
}
// Timeout extension: Wait for a limited time for someone else to
// take it, and take it if it's not taken.
// Returns true if resource is taken by someone else, false
// if it is taken back by the caller.
// This function must be called with both |giver_sect_| and
// |crit_sect_| held.
bool TakeBatonIfStillFree(int timeout_ms) {
bool not_timeout = true;
while (being_passed_ && not_timeout) {
not_timeout = cond_var_->SleepCS(*crit_sect_, timeout_ms);
// If we're woken up while variable is still held, we may have
// gotten a wakeup destined for a grabber thread.
// This situation is not treated specially here.
}
if (!being_passed_) {
return true;
} else {
assert(!not_timeout);
being_passed_ = false;
return false;
}
}
// Lock that ensures that there is only one thread in the active
// part of Pass() at a time.
// |giver_sect_| must always be acquired before |cond_var_|.
CriticalSectionWrapper* giver_sect_;
// Lock that protects |being_passed_|.
CriticalSectionWrapper* crit_sect_;
ConditionVariableWrapper* cond_var_;
bool being_passed_;
// Statistics information: Number of successfull passes.
int pass_count_;
};
// Function that waits on a Baton, and passes it right back.
// We expect these calls never to time out.
bool WaitingRunFunction(void* obj) {
Baton* the_baton = static_cast<Baton*> (obj);
EXPECT_TRUE(the_baton->Grab(kLongWaitMs));
EXPECT_TRUE(the_baton->Pass(kLongWaitMs));
return true;
}
class CondVarTest : public ::testing::Test {
public:
CondVarTest() {}
virtual void SetUp() {
thread_ = ThreadWrapper::CreateThread(&WaitingRunFunction,
&baton_);
unsigned int id = 42;
ASSERT_TRUE(thread_->Start(id));
}
virtual void TearDown() {
// We have to wake the thread in order to make it obey the stop order.
// But we don't know if the thread has completed the run function, so
// we don't know if it will exit before or after the Pass.
// Thus, we need to pin it down inside its Run function (between Grab
// and Pass).
ASSERT_TRUE(baton_.Pass(kShortWaitMs));
ASSERT_TRUE(baton_.Grab(kShortWaitMs));
ASSERT_TRUE(thread_->Stop());
delete thread_;
}
protected:
Baton baton_;
private:
ThreadWrapper* thread_;
};
// The SetUp and TearDown functions use condition variables.
// This test verifies those pieces in isolation.
// Disabled due to flakiness. See bug 4262 for details.
TEST_F(CondVarTest, DISABLED_InitFunctionsWork) {
// All relevant asserts are in the SetUp and TearDown functions.
}
// This test verifies that one can use the baton multiple times.
TEST_F(CondVarTest, DISABLED_PassBatonMultipleTimes) {
const int kNumberOfRounds = 2;
for (int i = 0; i < kNumberOfRounds; ++i) {
ASSERT_TRUE(baton_.Pass(kShortWaitMs));
ASSERT_TRUE(baton_.Grab(kShortWaitMs));
}
EXPECT_EQ(2 * kNumberOfRounds, baton_.PassCount());
}
} // anonymous namespace
} // namespace webrtc
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/X.h>
#include <png.h>
#include <zlib.h>
#include <jpeglib.h>
#include <vector>
#include "screenshot.h"
using namespace std;
// main() is where program execution begins.
int main() {
Display *display;
Window root;
int width = 0;
int height = 0;
XWindowAttributes gwa;
display = XOpenDisplay(NULL);
if (display == NULL) {
cout << "No display can be aquired" << endl;
return (1);
}
root = DefaultRootWindow(display);
XGetWindowAttributes(display, root, &gwa);
width = gwa.width;
height = gwa.height;
cout << "Width: " << width << "; Height: " << height << endl;
XImage *image = XGetImage(
display,
root,
0,
0,
width,
height,
AllPlanes,
ZPixmap
);
X11Screenshot screenshot = X11Screenshot(image);
if (screenshot.save_to_jpeg("test.jpg", 30))
cout << "saved jpeg" << endl;
if (screenshot.save_to_png("test.png"))
cout << "saved png" << endl;
XDestroyImage(image);
XCloseDisplay(display);
return 0;
}
<commit_msg>Add thumbnail example<commit_after>#include <iostream>
#include <cstdlib>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/X.h>
#include <png.h>
#include <zlib.h>
#include <jpeglib.h>
#include <vector>
#include "screenshot.h"
using namespace std;
// main() is where program execution begins.
int main() {
Display *display;
Window root;
int width = 0;
int height = 0;
XWindowAttributes gwa;
display = XOpenDisplay(NULL);
if (display == NULL) {
cout << "No display can be aquired" << endl;
return (1);
}
root = DefaultRootWindow(display);
XGetWindowAttributes(display, root, &gwa);
width = gwa.width;
height = gwa.height;
cout << "Width: " << width << "; Height: " << height << endl;
XImage *image = XGetImage(
display,
root,
0,
0,
width,
height,
AllPlanes,
ZPixmap
);
X11Screenshot screenshot = X11Screenshot(image);
cout << "x11 init" << endl;
if (screenshot.save_to_jpeg("test.jpg", 30))
cout << "saved jpeg" << endl;
if (screenshot.save_to_png("test.png"))
cout << "saved png" << endl;
X11Screenshot thumbnail = X11Screenshot(image, 1920, 540);
if (thumbnail.save_to_jpeg("thumb_test.jpg", 30))
cout << "saved thumbnail jpeg" << endl;
if (thumbnail.save_to_png("thumb_test.png"))
cout << "saved thumbnail png" << endl;
XDestroyImage(image);
XCloseDisplay(display);
return 0;
}
<|endoftext|> |
<commit_before>#include "AutonomousGroup4.h"
AutonomousGroup4::AutonomousGroup4()
{
//Goal: Pick up both bins on step with moose, drive back while setting them down
//Antlers move up, and fit in the auton zone somehow, either by turning or activating arms.
m_cMooseLifter1 = new AutonMooseLifter();
m_cAutonDrive1 = new AutonDriveStraight();
m_cAutonDrive2 = new AutonDriveStraight();
m_cAutonDumb1 = new AutonDumbDrive();
AddSequential(m_cAutonDrive1); //Drive backwards
AddSequential(m_cAutonDumb1); //Creep backwards slowly to ensure level with step
AddSequential(new WaitCommand(1.0));
AddSequential(m_cMooseLifter1); //Lift up both middle bins with moose
AddSequential(m_cAutonDrive2); //Drive forwards to the auton zone
}
AutonomousGroup4::~AutonomousGroup4()
{
delete m_cAutonDrive1;
delete m_cAutonDrive2;
delete m_cAutonDumb1;
delete m_cMooseLifter1;
}
// Called just before this Command runs the first time
void AutonomousGroup4::Initialize()
{
// Will change values once robot speed and positioning is known.
//Drive
m_cAutonDrive1->SetGoal(
-53,
1.5,
0.50,
3);
m_cAutonDrive2->SetGoal(
60,
1.5,
0.60,
7);
//Dumb Drive
m_cAutonDumb1->SetGoal(
0.50,
1);
//Moose Lifter
m_cMooseLifter1->SetGoal(0,
1.0,
true);
CommandBase::antlerMoose->ControlLeftAntler(true);
CommandBase::antlerMoose->ControlRightAntler(true);
CommandBase::mooseLifter->MoveMooseLock(false);
}
// Called repeatedly when this Command is scheduled to run
void AutonomousGroup4::Execute()
{
}
// Make this return true when this Command no longer needs to run execute()
bool AutonomousGroup4::IsFinished()
{
return false;
}
// Called once after isFinished returns true
void AutonomousGroup4::End()
{
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void AutonomousGroup4::Interrupted()
{
End();
}
<commit_msg>Mariucci latest change. Dumb speed decrease.<commit_after>#include "AutonomousGroup4.h"
AutonomousGroup4::AutonomousGroup4()
{
//Goal: Pick up both bins on step with moose, drive back while setting them down
//Antlers move up, and fit in the auton zone somehow, either by turning or activating arms.
m_cMooseLifter1 = new AutonMooseLifter();
m_cAutonDrive1 = new AutonDriveStraight();
m_cAutonDrive2 = new AutonDriveStraight();
m_cAutonDumb1 = new AutonDumbDrive();
AddSequential(m_cAutonDrive1); //Drive backwards
AddSequential(m_cAutonDumb1); //Creep backwards slowly to ensure level with step
AddSequential(new WaitCommand(1.0));
AddSequential(m_cMooseLifter1); //Lift up both middle bins with moose
AddSequential(m_cAutonDrive2); //Drive forwards to the auton zone
}
AutonomousGroup4::~AutonomousGroup4()
{
delete m_cAutonDrive1;
delete m_cAutonDrive2;
delete m_cAutonDumb1;
delete m_cMooseLifter1;
}
// Called just before this Command runs the first time
void AutonomousGroup4::Initialize()
{
// Will change values once robot speed and positioning is known.
//Drive
m_cAutonDrive1->SetGoal(
-53,
1.5,
0.50,
3);
m_cAutonDrive2->SetGoal(
60,
1.5,
0.60,
7);
//Dumb Drive
m_cAutonDumb1->SetGoal(
0.40,
1);
//Moose Lifter
m_cMooseLifter1->SetGoal(0,
1.0,
true);
CommandBase::antlerMoose->ControlLeftAntler(true);
CommandBase::antlerMoose->ControlRightAntler(true);
CommandBase::mooseLifter->MoveMooseLock(false);
}
// Called repeatedly when this Command is scheduled to run
void AutonomousGroup4::Execute()
{
}
// Make this return true when this Command no longer needs to run execute()
bool AutonomousGroup4::IsFinished()
{
return false;
}
// Called once after isFinished returns true
void AutonomousGroup4::End()
{
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void AutonomousGroup4::Interrupted()
{
End();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011, Roger Meier <[email protected]>
* 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 Roger Meier <[email protected]> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <string>
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <ctemplate/template.h>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;
#include "config.h"
#include "proxyme.tpl.varnames.h"
static std::string environment_mapper(const std::string &var_name) {
if (var_name == "HOME")
return var_name;
return "";
}
int main(int argc, char** argv) {
string proxy_user, proxy_pwd, proxy_host;
string configfile;
filesystem::path configdir;
int proxy_port = 0;
bool overwrite = false;
bool disable = false;
bool save = false;
bool urlencode = false;
filesystem::path home;
property_tree::ptree pt;
program_options::options_description desc("proxyme options");
desc.add_options()("help,h", "produce help message")
("user", program_options::value<string>(&proxy_user)->default_value(proxy_user),
"User (e.g. DOMAIN\\user)")
("password", program_options::value<string>(&proxy_pwd)->default_value(proxy_pwd),
"Password (e.g. 1234)")
("host", program_options::value<string>(&proxy_host)->default_value(proxy_host),
"Host (e.g. proxy.example.com)")
("port", program_options::value<int>(&proxy_port)->default_value(proxy_port),
"Port (e.g. 85)")
("disable,d", program_options::value<bool>(&disable)->zero_tokens(),
"Disable Proxy and overwrite all config files!")
("overwrite,o", program_options::value<bool>(&overwrite)->zero_tokens(),
"Overwriting files, don't care if they exist!")
("save,s", program_options::value<bool>(&save)->zero_tokens(),
"Save current parameters within proxyme.ini file")
("urlencode,u", program_options::value<bool>(&urlencode)->zero_tokens(),
"Store the password in URL encoded form")
("HOME", program_options::value<boost::filesystem::path>(&home)->default_value(home),
"Environment Variable: HOME");
program_options::variables_map options;
try {
program_options::store(program_options::parse_command_line(argc, argv, desc), options);
program_options::store(program_options::parse_environment(desc, &environment_mapper), options);
program_options::notify(options);
if (options.count("help")) {
cout << desc << endl;
return 1;
}
} catch (boost::program_options::unknown_option)
{
cout << "invalid option" << endl;
cout << "Try `proxyme --help' for more information." << endl;
return 1;
}
configdir = home.string() + CONFIGDIR;
configfile = configdir.string() + CONFIGFILENAME;
if (!filesystem::exists(configfile)) {
cout << "No configuration available, initialization of proxyme...";
if (filesystem::exists(DATADIR)) {
filesystem::create_directory(configdir);
filesystem::path dir = DATADIR;
filesystem::directory_iterator end_it;
for ( filesystem::directory_iterator it(dir); it != end_it; ++it) {
filesystem::path tartget_file_path = configdir;
tartget_file_path /= it->path().filename();
filesystem::copy_file(it->path(), tartget_file_path);
}
cout << " done." << endl;
cout << "Customize here: " << configdir.string() << endl;
return 0;
}
else {
cout << " error." << endl;
cout << "Template directory " << DATADIR << " does not exist, did you made a proper install?" << endl;
return 1;
}
}
read_ini(configfile, pt);
proxy_host = pt.get<string> ("proxyme.host", proxy_host);
proxy_port = pt.get<int> ("proxyme.port", proxy_port);
proxy_user = pt.get<string> ("proxyme.user", proxy_user);
proxy_pwd = pt.get<string> ("proxyme.password", proxy_pwd);
if(save) {
cout << "save host, port and user to proxyme.ini" << endl;
pt.put("proxyme.host", proxy_host);
pt.put("proxyme.port", proxy_port);
pt.put("proxyme.user", proxy_user);
write_ini(configfile, pt);
}
if(!disable) {
if (proxy_host.empty() || proxy_port == 0) {
cout << "Proxy host and port is required." << endl;
return 1;
}
if (!proxy_user.empty() && proxy_pwd.empty()) {
cout << "Password is required if user is defined!" << endl;
char *pass = getpass("Please enter password: ");
proxy_pwd = pass;
}
}
// fill the template dictionary
ctemplate::TemplateDictionary dict("proxyme");
dict.SetValue(kp_PROXY_HOST, proxy_host);
dict.SetIntValue(kp_PROXY_PORT, proxy_port);
if (!proxy_user.empty()) {
dict.SetValue(kp_PROXY_USER, proxy_user);
if ( urlencode ) {
// Replace each character of proxy_pwd with its hex value prependen by a % sign
// this is known as URL encoding (http://en.wikipedia.org/wiki/Percent-encoding)
// This allows to have special characters in the password and gives a basic protection
// against accidently revealing the password
char hex[3];
string enc_proxy_pwd = "";
int i, length = proxy_pwd.length();
for(i = 0; i < length; i++)
{
sprintf(hex, "%%%X",proxy_pwd[i]);
enc_proxy_pwd.append(hex);
}
proxy_pwd = enc_proxy_pwd;
}
dict.SetValue(kp_PROXY_PWD, proxy_pwd);
dict.ShowSection(kp_PROXY_AUTH);
}
if (disable) {
dict.SetValue(kp_PROXYME, "proxy disabled by proxyme");
cout << "Disable proxy" << endl;
overwrite = true;
} else {
dict.SetValue(kp_PROXYME, "proxy enabled by proxyme");
dict.ShowSection(kp_PROXY);
}
// read configuration
read_ini(configfile, pt);
for (property_tree::ptree::const_iterator it = pt.begin(); it != pt.end(); it++) {
// ignore config section
if(it->first == "proxyme") {
continue;
}
string template_file = pt.get<string> (it->first + ".template");
string target_file = pt.get<string> (it->first + ".target");
if (!home.empty()) {
regex pattern("[$][(](HOME)[)]", boost::regex_constants::perl);
template_file = boost::regex_replace(template_file, pattern, home.string());
target_file = boost::regex_replace(target_file, pattern, home.string());
}
if (pt.get_optional<bool> (it->first + ".escape_backslash")) {
regex pattern("\\\\", boost::regex_constants::perl);
string escaped_user = boost::regex_replace(proxy_user, pattern, "\\\\\\");
dict.SetValue(kp_PROXY_USER, escaped_user);
}
if (filesystem::exists(target_file) && !overwrite) {
cout << target_file << " exists, leave it untouched." << endl;
} else {
if (filesystem::exists(target_file) && overwrite) {
cout << "overwrite " << target_file << endl;
} else {
cout << "write " << target_file << endl;
}
string output;
ofstream genfile;
ctemplate::ExpandTemplate(template_file, ctemplate::DO_NOT_STRIP, &dict, &output);
genfile.open(target_file.c_str());
genfile << output;
genfile.close();
}
}
return 0;
}
<commit_msg>fix: create parent dir if not existing<commit_after>/*
* Copyright (c) 2011, Roger Meier <[email protected]>
* 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 Roger Meier <[email protected]> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <string>
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <ctemplate/template.h>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;
#include "config.h"
#include "proxyme.tpl.varnames.h"
static std::string environment_mapper(const std::string &var_name) {
if (var_name == "HOME")
return var_name;
return "";
}
int main(int argc, char** argv) {
string proxy_user, proxy_pwd, proxy_host;
string configfile;
filesystem::path configdir;
int proxy_port = 0;
bool overwrite = false;
bool disable = false;
bool save = false;
bool urlencode = false;
filesystem::path home;
property_tree::ptree pt;
program_options::options_description desc("proxyme options");
desc.add_options()("help,h", "produce help message")
("user", program_options::value<string>(&proxy_user)->default_value(proxy_user),
"User (e.g. DOMAIN\\user)")
("password", program_options::value<string>(&proxy_pwd)->default_value(proxy_pwd),
"Password (e.g. 1234)")
("host", program_options::value<string>(&proxy_host)->default_value(proxy_host),
"Host (e.g. proxy.example.com)")
("port", program_options::value<int>(&proxy_port)->default_value(proxy_port),
"Port (e.g. 85)")
("disable,d", program_options::value<bool>(&disable)->zero_tokens(),
"Disable Proxy and overwrite all config files!")
("overwrite,o", program_options::value<bool>(&overwrite)->zero_tokens(),
"Overwriting files, don't care if they exist!")
("save,s", program_options::value<bool>(&save)->zero_tokens(),
"Save current parameters within proxyme.ini file")
("urlencode,u", program_options::value<bool>(&urlencode)->zero_tokens(),
"Store the password in URL encoded form")
("HOME", program_options::value<boost::filesystem::path>(&home)->default_value(home),
"Environment Variable: HOME");
program_options::variables_map options;
try {
program_options::store(program_options::parse_command_line(argc, argv, desc), options);
program_options::store(program_options::parse_environment(desc, &environment_mapper), options);
program_options::notify(options);
if (options.count("help")) {
cout << desc << endl;
return 1;
}
} catch (boost::program_options::unknown_option)
{
cout << "invalid option" << endl;
cout << "Try `proxyme --help' for more information." << endl;
return 1;
}
configdir = home.string() + CONFIGDIR;
configfile = configdir.string() + CONFIGFILENAME;
if (!filesystem::exists(configfile)) {
cout << "No configuration available, initialization of proxyme...";
if (filesystem::exists(DATADIR)) {
filesystem::create_directory(configdir);
filesystem::path dir = DATADIR;
filesystem::directory_iterator end_it;
for ( filesystem::directory_iterator it(dir); it != end_it; ++it) {
filesystem::path tartget_file_path = configdir;
tartget_file_path /= it->path().filename();
filesystem::copy_file(it->path(), tartget_file_path);
}
cout << " done." << endl;
cout << "Customize here: " << configdir.string() << endl;
return 0;
}
else {
cout << " error." << endl;
cout << "Template directory " << DATADIR << " does not exist, did you made a proper install?" << endl;
return 1;
}
}
read_ini(configfile, pt);
proxy_host = pt.get<string> ("proxyme.host", proxy_host);
proxy_port = pt.get<int> ("proxyme.port", proxy_port);
proxy_user = pt.get<string> ("proxyme.user", proxy_user);
proxy_pwd = pt.get<string> ("proxyme.password", proxy_pwd);
if(save) {
cout << "save host, port and user to proxyme.ini" << endl;
pt.put("proxyme.host", proxy_host);
pt.put("proxyme.port", proxy_port);
pt.put("proxyme.user", proxy_user);
write_ini(configfile, pt);
}
if(!disable) {
if (proxy_host.empty() || proxy_port == 0) {
cout << "Proxy host and port is required." << endl;
return 1;
}
if (!proxy_user.empty() && proxy_pwd.empty()) {
cout << "Password is required if user is defined!" << endl;
char *pass = getpass("Please enter password: ");
proxy_pwd = pass;
}
}
// fill the template dictionary
ctemplate::TemplateDictionary dict("proxyme");
dict.SetValue(kp_PROXY_HOST, proxy_host);
dict.SetIntValue(kp_PROXY_PORT, proxy_port);
if (!proxy_user.empty()) {
dict.SetValue(kp_PROXY_USER, proxy_user);
if ( urlencode ) {
// Replace each character of proxy_pwd with its hex value prependen by a % sign
// this is known as URL encoding (http://en.wikipedia.org/wiki/Percent-encoding)
// This allows to have special characters in the password and gives a basic protection
// against accidently revealing the password
char hex[3];
string enc_proxy_pwd = "";
int i, length = proxy_pwd.length();
for(i = 0; i < length; i++)
{
sprintf(hex, "%%%X",proxy_pwd[i]);
enc_proxy_pwd.append(hex);
}
proxy_pwd = enc_proxy_pwd;
}
dict.SetValue(kp_PROXY_PWD, proxy_pwd);
dict.ShowSection(kp_PROXY_AUTH);
}
if (disable) {
dict.SetValue(kp_PROXYME, "proxy disabled by proxyme");
cout << "Disable proxy" << endl;
overwrite = true;
} else {
dict.SetValue(kp_PROXYME, "proxy enabled by proxyme");
dict.ShowSection(kp_PROXY);
}
// read configuration
read_ini(configfile, pt);
for (property_tree::ptree::const_iterator it = pt.begin(); it != pt.end(); it++) {
// ignore config section
if(it->first == "proxyme") {
continue;
}
string template_file = pt.get<string> (it->first + ".template");
string target_file = pt.get<string> (it->first + ".target");
if (!home.empty()) {
regex pattern("[$][(](HOME)[)]", boost::regex_constants::perl);
template_file = boost::regex_replace(template_file, pattern, home.string());
target_file = boost::regex_replace(target_file, pattern, home.string());
}
if (pt.get_optional<bool> (it->first + ".escape_backslash")) {
regex pattern("\\\\", boost::regex_constants::perl);
string escaped_user = boost::regex_replace(proxy_user, pattern, "\\\\\\");
dict.SetValue(kp_PROXY_USER, escaped_user);
}
if (filesystem::exists(target_file) && !overwrite) {
cout << target_file << " exists, leave it untouched." << endl;
} else {
if (filesystem::exists(target_file) && overwrite) {
cout << "overwrite " << target_file << endl;
} else {
cout << "write " << target_file << endl;
filesystem::path pathname(target_file);
filesystem::path dir(pathname.parent_path().string());
if(!(boost::filesystem::exists(dir))){
if (boost::filesystem::create_directory(dir))
std::cout << "non existing parent dir(" << dir << ") created!" << std::endl;
}
}
string output;
ofstream genfile;
ctemplate::ExpandTemplate(template_file, ctemplate::DO_NOT_STRIP, &dict, &output);
genfile.open(target_file.c_str());
genfile << output;
genfile.close();
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include "source/common/runtime/runtime_features.h"
#include "absl/strings/match.h"
namespace Envoy {
namespace Runtime {
bool isRuntimeFeature(absl::string_view feature) {
return RuntimeFeaturesDefaults::get().enabledByDefault(feature) ||
RuntimeFeaturesDefaults::get().existsButDisabled(feature);
}
bool runtimeFeatureEnabled(absl::string_view feature) {
ASSERT(isRuntimeFeature(feature));
if (Runtime::LoaderSingleton::getExisting()) {
return Runtime::LoaderSingleton::getExisting()->threadsafeSnapshot()->runtimeFeatureEnabled(
feature);
}
ENVOY_LOG_TO_LOGGER(Envoy::Logger::Registry::getLog(Envoy::Logger::Id::runtime), debug,
"Unable to use runtime singleton for feature {}", feature);
return RuntimeFeaturesDefaults::get().enabledByDefault(feature);
}
uint64_t getInteger(absl::string_view feature, uint64_t default_value) {
ASSERT(absl::StartsWith(feature, "envoy."));
if (Runtime::LoaderSingleton::getExisting()) {
return Runtime::LoaderSingleton::getExisting()->threadsafeSnapshot()->getInteger(
std::string(feature), default_value);
}
ENVOY_LOG_TO_LOGGER(Envoy::Logger::Registry::getLog(Envoy::Logger::Id::runtime), debug,
"Unable to use runtime singleton for feature {}", feature);
return default_value;
}
// Add additional features here to enable the new code paths by default.
//
// Per documentation in CONTRIBUTING.md is expected that new high risk code paths be guarded
// by runtime feature guards, i.e
//
// if (Runtime::runtimeFeatureEnabled("envoy.reloadable_features.my_feature_name")) {
// [new code path]
// else {
// [old_code_path]
// }
//
// Runtime features are false by default, so the old code path is exercised.
// To make a runtime feature true by default, add it to the array below.
// New features should be true-by-default for an Envoy release cycle before the
// old code path is removed.
//
// If issues are found that require a runtime feature to be disabled, it should be reported
// ASAP by filing a bug on github. Overriding non-buggy code is strongly discouraged to avoid the
// problem of the bugs being found after the old code path has been removed.
// clang-format off
constexpr const char* runtime_features[] = {
// Enabled
"envoy.reloadable_features.test_feature_true",
// Begin alphabetically sorted section.
"envoy.reloadable_features.allow_response_for_timeout",
"envoy.reloadable_features.allow_upstream_inline_write",
"envoy.reloadable_features.conn_pool_delete_when_idle",
"envoy.reloadable_features.correct_scheme_and_xfp",
"envoy.reloadable_features.correctly_validate_alpn",
"envoy.reloadable_features.disable_tls_inspector_injection",
"envoy.reloadable_features.enable_grpc_async_client_cache",
"envoy.reloadable_features.fix_added_trailers",
"envoy.reloadable_features.handle_stream_reset_during_hcm_encoding",
"envoy.reloadable_features.http2_allow_capacity_increase_by_settings",
"envoy.reloadable_features.http2_new_codec_wrapper",
"envoy.reloadable_features.http_ext_authz_do_not_skip_direct_response_and_redirect",
"envoy.reloadable_features.http_reject_path_with_fragment",
"envoy.reloadable_features.http_strip_fragment_from_path_unsafe_if_disabled",
"envoy.reloadable_features.internal_address",
"envoy.reloadable_features.internal_redirects_with_body",
"envoy.reloadable_features.listener_reuse_port_default_enabled",
"envoy.reloadable_features.listener_wildcard_match_ip_family",
"envoy.reloadable_features.new_tcp_connection_pool",
"envoy.reloadable_features.proxy_102_103",
"envoy.reloadable_features.remove_legacy_json",
"envoy.reloadable_features.support_locality_update_on_eds_cluster_endpoints",
"envoy.reloadable_features.udp_listener_updates_filter_chain_in_place",
"envoy.reloadable_features.update_expected_rq_timeout_on_retry",
"envoy.reloadable_features.use_dns_ttl",
"envoy.reloadable_features.validate_connect",
"envoy.reloadable_features.vhds_heartbeats",
"envoy.restart_features.explicit_wildcard_resource",
"envoy.restart_features.use_apple_api_for_dns_lookups",
// Misplaced flags: please do not add flags to this section.
"envoy.reloadable_features.sanitize_http_header_referer",
"envoy.reloadable_features.skip_dispatching_frames_for_closed_connection",
// End misplaced flags: please do not add flags in this section.
};
// clang-format on
// This is a section for officially sanctioned runtime features which are too
// high risk to be enabled by default. Examples where we have opted to land
// features without enabling by default are swapping the underlying buffer
// implementation or the HTTP/1.1 codec implementation. Most features should be
// enabled by default.
//
// When features are added here, there should be a tracking bug assigned to the
// code owner to flip the default after sufficient testing.
constexpr const char* disabled_runtime_features[] = {
// TODO(alyssawilk, junr03) flip (and add release notes + docs) these after Lyft tests
"envoy.reloadable_features.allow_multiple_dns_addresses",
// Sentinel and test flag.
"envoy.reloadable_features.test_feature_false",
// TODO(dmitri-d) reset to true to enable unified mux by default
"envoy.reloadable_features.unified_mux",
};
RuntimeFeatures::RuntimeFeatures() {
for (auto& feature : runtime_features) {
enabled_features_.insert(feature);
}
for (auto& feature : disabled_runtime_features) {
disabled_features_.insert(feature);
}
}
} // namespace Runtime
} // namespace Envoy
<commit_msg>runtime: flipping http2_new_codec_wrapper false (#19770)<commit_after>#include "source/common/runtime/runtime_features.h"
#include "absl/strings/match.h"
namespace Envoy {
namespace Runtime {
bool isRuntimeFeature(absl::string_view feature) {
return RuntimeFeaturesDefaults::get().enabledByDefault(feature) ||
RuntimeFeaturesDefaults::get().existsButDisabled(feature);
}
bool runtimeFeatureEnabled(absl::string_view feature) {
ASSERT(isRuntimeFeature(feature));
if (Runtime::LoaderSingleton::getExisting()) {
return Runtime::LoaderSingleton::getExisting()->threadsafeSnapshot()->runtimeFeatureEnabled(
feature);
}
ENVOY_LOG_TO_LOGGER(Envoy::Logger::Registry::getLog(Envoy::Logger::Id::runtime), debug,
"Unable to use runtime singleton for feature {}", feature);
return RuntimeFeaturesDefaults::get().enabledByDefault(feature);
}
uint64_t getInteger(absl::string_view feature, uint64_t default_value) {
ASSERT(absl::StartsWith(feature, "envoy."));
if (Runtime::LoaderSingleton::getExisting()) {
return Runtime::LoaderSingleton::getExisting()->threadsafeSnapshot()->getInteger(
std::string(feature), default_value);
}
ENVOY_LOG_TO_LOGGER(Envoy::Logger::Registry::getLog(Envoy::Logger::Id::runtime), debug,
"Unable to use runtime singleton for feature {}", feature);
return default_value;
}
// Add additional features here to enable the new code paths by default.
//
// Per documentation in CONTRIBUTING.md is expected that new high risk code paths be guarded
// by runtime feature guards, i.e
//
// if (Runtime::runtimeFeatureEnabled("envoy.reloadable_features.my_feature_name")) {
// [new code path]
// else {
// [old_code_path]
// }
//
// Runtime features are false by default, so the old code path is exercised.
// To make a runtime feature true by default, add it to the array below.
// New features should be true-by-default for an Envoy release cycle before the
// old code path is removed.
//
// If issues are found that require a runtime feature to be disabled, it should be reported
// ASAP by filing a bug on github. Overriding non-buggy code is strongly discouraged to avoid the
// problem of the bugs being found after the old code path has been removed.
// clang-format off
constexpr const char* runtime_features[] = {
// Enabled
"envoy.reloadable_features.test_feature_true",
// Begin alphabetically sorted section.
"envoy.reloadable_features.allow_response_for_timeout",
"envoy.reloadable_features.allow_upstream_inline_write",
"envoy.reloadable_features.conn_pool_delete_when_idle",
"envoy.reloadable_features.correct_scheme_and_xfp",
"envoy.reloadable_features.correctly_validate_alpn",
"envoy.reloadable_features.disable_tls_inspector_injection",
"envoy.reloadable_features.enable_grpc_async_client_cache",
"envoy.reloadable_features.fix_added_trailers",
"envoy.reloadable_features.handle_stream_reset_during_hcm_encoding",
"envoy.reloadable_features.http2_allow_capacity_increase_by_settings",
"envoy.reloadable_features.http_ext_authz_do_not_skip_direct_response_and_redirect",
"envoy.reloadable_features.http_reject_path_with_fragment",
"envoy.reloadable_features.http_strip_fragment_from_path_unsafe_if_disabled",
"envoy.reloadable_features.internal_address",
"envoy.reloadable_features.internal_redirects_with_body",
"envoy.reloadable_features.listener_reuse_port_default_enabled",
"envoy.reloadable_features.listener_wildcard_match_ip_family",
"envoy.reloadable_features.new_tcp_connection_pool",
"envoy.reloadable_features.proxy_102_103",
"envoy.reloadable_features.remove_legacy_json",
"envoy.reloadable_features.support_locality_update_on_eds_cluster_endpoints",
"envoy.reloadable_features.udp_listener_updates_filter_chain_in_place",
"envoy.reloadable_features.update_expected_rq_timeout_on_retry",
"envoy.reloadable_features.use_dns_ttl",
"envoy.reloadable_features.validate_connect",
"envoy.reloadable_features.vhds_heartbeats",
"envoy.restart_features.explicit_wildcard_resource",
"envoy.restart_features.use_apple_api_for_dns_lookups",
// Misplaced flags: please do not add flags to this section.
"envoy.reloadable_features.sanitize_http_header_referer",
"envoy.reloadable_features.skip_dispatching_frames_for_closed_connection",
// End misplaced flags: please do not add flags in this section.
};
// clang-format on
// This is a section for officially sanctioned runtime features which are too
// high risk to be enabled by default. Examples where we have opted to land
// features without enabling by default are swapping the underlying buffer
// implementation or the HTTP/1.1 codec implementation. Most features should be
// enabled by default.
//
// When features are added here, there should be a tracking bug assigned to the
// code owner to flip the default after sufficient testing.
constexpr const char* disabled_runtime_features[] = {
// TODO(alyssawilk, junr03) flip (and add release notes + docs) these after Lyft tests
"envoy.reloadable_features.allow_multiple_dns_addresses",
// Sentinel and test flag.
"envoy.reloadable_features.test_feature_false",
// TODO(dmitri-d) reset to true to enable unified mux by default
"envoy.reloadable_features.unified_mux",
// TODO(birenroy) flip after https://github.com/envoyproxy/envoy/issues/19761 sorted.
"envoy.reloadable_features.http2_new_codec_wrapper",
};
RuntimeFeatures::RuntimeFeatures() {
for (auto& feature : runtime_features) {
enabled_features_.insert(feature);
}
for (auto& feature : disabled_runtime_features) {
disabled_features_.insert(feature);
}
}
} // namespace Runtime
} // namespace Envoy
<|endoftext|> |
<commit_before>//
// main.cpp
// thermaleraser
//
// Created by Mark Larus on 9/8/12.
// Copyright (c) 2012 Kenyon College. All rights reserved.
//
#include <omp.h>
#include <iostream>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf.h>
#include <time.h>
#include <semaphore.h>
#include <algorithm>
#include <math.h>
#include <sqlite3.h>
#include <assert.h>
#include <set>
#include <boost/program_options.hpp>
#include <boost/timer/timer.hpp>
#include "States.h"
#include "System.h"
#include "Utilities.h"
#define print(x) std::cout<<#x <<": " <<x<<std::endl;
namespace opt = boost::program_options;
enum OutputType {
CommaSeparated,
PrettyPrint,
Mathematica,
NoOutput
};
void simulate_and_print(Constants constants, int iterations, OutputType type);
int main(int argc, char * argv[]) {
/*! Initialize options list.
*/
bool verbose = false;
const int default_iterations = 1<<16;
opt::options_description desc("Allowed options");
desc.add_options()
("iterations,n",opt::value<int>(), "Number of iterations")
("help","Show help message")
("verbose,v", "Show extensive debugging info")
("output,o", opt::value<int>(), "Output style.");
;
opt::variables_map vmap;
opt::store(opt::parse_command_line(argc,argv,desc),vmap);
opt::notify(vmap);
if (vmap.count("help")) {
std::cout << desc << "\n";
return 1;
}
verbose = vmap.count("verbose");
int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations;
if (verbose) {
print(iterations);
#pragma omp parallel
#pragma omp single
print(omp_get_num_threads());
}
OutputType output_style = vmap.count("output") ? (OutputType)vmap["output"].as<int>() : CommaSeparated;
/*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is
represented by an object with pointers to the next states and the bit-flip states. */
setupStates();
Constants constants;
/*! The delta used here is NOT, at this point, the delta used in the paper. This is the
ratio of ones to zeroes in the bit stream. Probably worth changing the name, but
calculating this at runtime is just an invitation for bugs. */
constants.delta = .5;
constants.epsilon = .7;
constants.tau = 1;
int dimension = 50;
for (int k=dimension*dimension; k>=0; k--) {
constants.epsilon = (k % dimension)/(double)(dimension);
constants.delta = .5 + .5*(k / dimension)/(double)(dimension);
simulate_and_print(constants, iterations, output_style);
}
}
void simulate_and_print(Constants constants, int iterations, OutputType type) {
boost::timer::auto_cpu_timer t;
/*! Use this to change the length of the tape. */
const int BIT_STREAM_LENGTH = 8;
int first_pass_iterations = iterations;
System *systems = new System[first_pass_iterations];
int *histogram = new int[1<<BIT_STREAM_LENGTH];
std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);
long double *p = new long double[1<<BIT_STREAM_LENGTH];
long double *p_prime = new long double[1<<BIT_STREAM_LENGTH];
long double sum = 0;
const long double beta = log((1+constants.epsilon)/(1-constants.epsilon));
long double max_surprise = 0;
long double min_surprise = LONG_MAX;
#pragma omp parallel
{
//TODO: Move this into a semaphore in the utility function
gsl_rng *localRNG = GSLRandomNumberGenerator();
#pragma omp for
for (int k=0; k<first_pass_iterations; ++k) {
System *currentSystem = systems+k;
currentSystem->constants = constants;
currentSystem->nbits = BIT_STREAM_LENGTH;
evolveSystem(currentSystem, localRNG);
histogram[systems[k].endingBitString]++;
}
#pragma omp single nowait
delete [] systems;
#pragma omp for nowait
for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) {
int setBits = bitCount(k,BIT_STREAM_LENGTH);
p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits);
p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations);
}
#pragma omp single nowait
delete [] histogram;
#pragma omp barrier
//Make sure we don't accidentally share a seed.
#pragma omp for reduction(+ : sum)
for(int k=0; k<iterations; k++) {
System *currentSystem = new System();
currentSystem->constants = constants;
currentSystem->nbits = BIT_STREAM_LENGTH;
evolveSystem(currentSystem, localRNG);
long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString];
max_surprise = surprise > max_surprise ? surprise : max_surprise;
min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise;
sum = sum + surprise;
delete currentSystem;
}
#pragma omp single nowait
{
delete [] p_prime;
delete [] p;
if(type==CommaSeparated) {
static int once = 0;
if (!once) {
std::cout<<"delta,epsilon,avg,max_surprise\n";
once=1;
}
std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl;
}
if(type==PrettyPrint) {
print(beta);
print(constants.delta);
print(constants.epsilon);
print(sum/iterations);
print(max_surprise);
print(sum);
std::cout<<std::endl;
}
if (type==Mathematica) {
assert(0);
}
}
gsl_rng_free(localRNG);
}
}
<commit_msg>Add an -o flag for output style.<commit_after>//
// main.cpp
// thermaleraser
//
// Created by Mark Larus on 9/8/12.
// Copyright (c) 2012 Kenyon College. All rights reserved.
//
#include <omp.h>
#include <iostream>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf.h>
#include <time.h>
#include <semaphore.h>
#include <algorithm>
#include <math.h>
#include <sqlite3.h>
#include <assert.h>
#include <set>
#include <boost/program_options.hpp>
#include <boost/timer/timer.hpp>
#include "States.h"
#include "System.h"
#include "Utilities.h"
#define print(x) std::cout<<#x <<": " <<x<<std::endl;
namespace opt = boost::program_options;
enum OutputType {
CommaSeparated,
PrettyPrint,
Mathematica,
NoOutput
};
void simulate_and_print(Constants constants, int iterations, OutputType type);
int main(int argc, char * argv[]) {
/*! Initialize options list.
*/
bool verbose = false;
const int default_iterations = 1<<16;
opt::options_description desc("Allowed options");
desc.add_options()
("iterations,n",opt::value<int>(), "Number of iterations")
("help","Show help message")
("verbose,v", "Show extensive debugging info")
("output,o", opt::value<int>(), "Output style.");
;
opt::variables_map vmap;
opt::store(opt::parse_command_line(argc,argv,desc),vmap);
opt::notify(vmap);
if (vmap.count("help")) {
std::cout << desc << "\n";
return 1;
}
verbose = vmap.count("verbose");
int iterations = vmap.count("iterations") ? vmap["iterations"].as<int>() : default_iterations;
if (verbose) {
print(iterations);
#pragma omp parallel
#pragma omp single
print(omp_get_num_threads());
}
OutputType output_style = vmap.count("output") ? (OutputType)vmap["output"].as<int>() : CommaSeparated;
/*! This call sets up our state machine for the wheel. Each state (i.e. "A0", "C1") is
represented by an object with pointers to the next states and the bit-flip states. */
setupStates();
Constants constants;
/*! The delta used here is NOT, at this point, the delta used in the paper. This is the
ratio of ones to zeroes in the bit stream. Probably worth changing the name, but
calculating this at runtime is just an invitation for bugs. */
constants.delta = .5;
constants.epsilon = .7;
constants.tau = 1;
int dimension = 50;
for (int k=dimension*dimension; k>=0; k--) {
constants.epsilon = (k % dimension)/(double)(dimension);
constants.delta = .5 + .5*(k / dimension)/(double)(dimension);
simulate_and_print(constants, iterations, output_style);
}
}
void simulate_and_print(Constants constants, int iterations, OutputType type) {
boost::timer::auto_cpu_timer t;
/*! Use this to change the length of the tape. */
const int BIT_STREAM_LENGTH = 8;
int first_pass_iterations = iterations;
System *systems = new System[first_pass_iterations];
int *histogram = new int[1<<BIT_STREAM_LENGTH];
std::fill_n(histogram, 1<<BIT_STREAM_LENGTH, 0);
long double *p = new long double[1<<BIT_STREAM_LENGTH];
long double *p_prime = new long double[1<<BIT_STREAM_LENGTH];
long double sum = 0;
const long double beta = log((1+constants.epsilon)/(1-constants.epsilon));
long double max_surprise = 0;
long double min_surprise = LONG_MAX;
#pragma omp parallel
{
//TODO: Move this into a semaphore in the utility function
gsl_rng *localRNG = GSLRandomNumberGenerator();
#pragma omp for
for (int k=0; k<first_pass_iterations; ++k) {
System *currentSystem = systems+k;
currentSystem->constants = constants;
currentSystem->nbits = BIT_STREAM_LENGTH;
evolveSystem(currentSystem, localRNG);
histogram[systems[k].endingBitString]++;
}
#pragma omp single nowait
delete [] systems;
#pragma omp for nowait
for(int k=0; k<1<<BIT_STREAM_LENGTH; k++) {
int setBits = bitCount(k,BIT_STREAM_LENGTH);
p[k] = gsl_ran_binomial_pdf(setBits, constants.delta, BIT_STREAM_LENGTH)/gsl_sf_choose(BIT_STREAM_LENGTH,setBits);
p_prime[k]=static_cast<long double>(histogram[k])/(first_pass_iterations);
}
#pragma omp single nowait
delete [] histogram;
#pragma omp barrier
//Make sure we don't accidentally share a seed.
#pragma omp for reduction(+ : sum)
for(int k=0; k<iterations; k++) {
System *currentSystem = new System();
currentSystem->constants = constants;
currentSystem->nbits = BIT_STREAM_LENGTH;
evolveSystem(currentSystem, localRNG);
long double surprise = exp(beta*currentSystem->mass)*p_prime[currentSystem->endingBitString]/p[currentSystem->startingBitString];
max_surprise = surprise > max_surprise ? surprise : max_surprise;
min_surprise = surprise && surprise < min_surprise ? surprise : min_surprise;
sum = sum + surprise;
delete currentSystem;
}
#pragma omp single nowait
{
delete [] p_prime;
delete [] p;
if(type==CommaSeparated) {
static int once = 0;
if (!once) {
std::cout<<"delta,epsilon,avg,max_surprise\n";
once=1;
}
std::cout<< constants.delta << "," << constants.epsilon << "," << sum/iterations << "," << max_surprise << std::endl;
}
if(type==PrettyPrint) {
print(beta);
print(constants.delta);
print(constants.epsilon);
print(sum/iterations);
print(max_surprise);
print(sum);
std::cout<<std::endl;
}
if (type==Mathematica) {
assert(0);
}
}
gsl_rng_free(localRNG);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: macros.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2007-07-25 08:48:28 $
*
* 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 CHART_MACROS_HXX
#define CHART_MACROS_HXX
#include <typeinfo>
/// creates a unicode-string from an ASCII string
#define C2U(constAsciiStr) (::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( constAsciiStr ) ))
/** shows an error-box for an exception ex
else-branch necessary to avoid warning
*/
#if OSL_DEBUG_LEVEL > 0
#define ASSERT_EXCEPTION(ex) \
OSL_ENSURE( false, ::rtl::OUStringToOString( \
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Exception caught. Type: " )) +\
::rtl::OUString::createFromAscii( typeid( ex ).name()) +\
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ", Message: " )) +\
ex.Message, RTL_TEXTENCODING_ASCII_US ).getStr())
#else
//avoid compilation warnings
#define ASSERT_EXCEPTION(ex) (void)(ex);
#endif
#define U2C(ouString) (::rtl::OUStringToOString(ouString,RTL_TEXTENCODING_ASCII_US).getStr())
// CHART_MACROS_HXX
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.94); FILE MERGED 2008/03/28 16:43:58 rt 1.4.94.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: macros.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef CHART_MACROS_HXX
#define CHART_MACROS_HXX
#include <typeinfo>
/// creates a unicode-string from an ASCII string
#define C2U(constAsciiStr) (::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( constAsciiStr ) ))
/** shows an error-box for an exception ex
else-branch necessary to avoid warning
*/
#if OSL_DEBUG_LEVEL > 0
#define ASSERT_EXCEPTION(ex) \
OSL_ENSURE( false, ::rtl::OUStringToOString( \
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Exception caught. Type: " )) +\
::rtl::OUString::createFromAscii( typeid( ex ).name()) +\
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ", Message: " )) +\
ex.Message, RTL_TEXTENCODING_ASCII_US ).getStr())
#else
//avoid compilation warnings
#define ASSERT_EXCEPTION(ex) (void)(ex);
#endif
#define U2C(ouString) (::rtl::OUStringToOString(ouString,RTL_TEXTENCODING_ASCII_US).getStr())
// CHART_MACROS_HXX
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005-2017 by Centre National d'Etudes Spatiales (CNES)
*
* This file is licensed under MIT license:
*
* 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 <ossimSentinel1SarSensorModel.h>
#include <ossim/base/ossimXmlDocument.h>
#include "ossim/ossimXmlTools.h"
namespace {// Anonymous namespace
const ossimString attAzimuthTime = "azimuthTime";
const ossimString attFirstValidSample = "firstValidSample";
const ossimString attLastValidSample = "lastValidSample";
const ossimString attGr0 = "gr0";
const ossimString attGrsrCoefficients = "grsrCoefficients";
const ossimString attHeight = "height";
const ossimString attLatitude = "latitude";
const ossimString attLine = "line";
const ossimString attLongitude = "longitude";
const ossimString attPixel = "pixel";
const ossimString attPosition = "position";
const ossimString attSlantRangeTime = "slantRangeTime";
const ossimString attSr0 = "sr0";
const ossimString attSrgrCoefficients = "srgrCoefficients";
const ossimString attTime = "time";
const ossimString attVelocity = "velocity";
const ossimString attX = "x";
const ossimString attY = "y";
const ossimString attZ = "z";
}// Anonymous namespace
#if defined(USE_BOOST_TIME)
using boost::posix_time::microseconds;
using boost::posix_time::seconds;
#else
using ossimplugins::time::microseconds;
using ossimplugins::time::seconds;
#endif
void ossimplugins::ossimSentinel1SarSensorModel::readCoordinates(
ossimXmlDocument const& xmlDoc, ossimString const& xpath,
ossimString const& rg0_xpath, ossimString const& coeffs_xpath,
std::vector<CoordinateConversionRecordType> & outputRecords)
{
std::vector<ossimRefPtr<ossimXmlNode> > xnodes;
xmlDoc.findNodes(xpath, xnodes);
for(std::vector<ossimRefPtr<ossimXmlNode> >::iterator itNode = xnodes.begin(); itNode!=xnodes.end();++itNode)
{
CoordinateConversionRecordType coordRecord;
coordRecord.azimuthTime = getTimeFromFirstNode(**itNode, attAzimuthTime);
coordRecord.rg0 = getDoubleFromFirstNode(**itNode, rg0_xpath);;
ossimString const& s = getTextFromFirstNode(**itNode, coeffs_xpath);
std::vector<ossimString> ssplit = s.split(" ");
if (ssplit.empty())
{
throw std::runtime_error(("The "+rg0_xpath+" record has an empty coef vector").string());
}
for (std::vector<ossimString>::const_iterator cIt = ssplit.begin(), e = ssplit.end()
; cIt != e
; ++cIt
)
{
coordRecord.coefs.push_back(cIt->toDouble());
}
assert(!coordRecord.coefs.empty()&&"The rg0 record has empty coefs vector.");
outputRecords.push_back(coordRecord);
}
}
namespace ossimplugins
{
void ossimSentinel1SarSensorModel::readAnnotationFile(const std::string & annotationXml)
{
ossimRefPtr<ossimXmlDocument> xmlDoc = new ossimXmlDocument(annotationXml);
const ossimXmlNode & xmlRoot = *xmlDoc->getRoot();
//Parse specific metadata for Sentinel1
//TODO add as members to the Sentinel1SarSensorModel
const std::string & product_type = getTextFromFirstNode(xmlRoot, "adsHeader/productType");
const std::string & mode = getTextFromFirstNode(xmlRoot, "adsHeader/mode");
const std::string & swath = getTextFromFirstNode(xmlRoot, "adsHeader/swath");
const std::string & polarisation = getTextFromFirstNode(xmlRoot, "adsHeader/polarisation");
theProductType = ProductType(product_type);
// First, lookup position/velocity records
std::vector<ossimRefPtr<ossimXmlNode> > xnodes;
xmlDoc->findNodes("/product/generalAnnotation/orbitList/orbit",xnodes);
//TODO uncomment and adapt following code from s1_inverse to fill
//SarSensorModel structure
for(std::vector<ossimRefPtr<ossimXmlNode> >::iterator itNode = xnodes.begin(); itNode!=xnodes.end();++itNode)
{
OrbitRecordType orbitRecord;
// Retrieve acquisition time
orbitRecord.azimuthTime = getTimeFromFirstNode(**itNode, attTime);
// Retrieve ECEF position
ossimXmlNode const& positionNode = getExpectedFirstNode(**itNode, attPosition);
orbitRecord.position[0] = getDoubleFromFirstNode(positionNode, attX);
orbitRecord.position[1] = getDoubleFromFirstNode(positionNode, attY);
orbitRecord.position[2] = getDoubleFromFirstNode(positionNode, attZ);
// Retrieve ECEF velocity
ossimXmlNode const& velocityNode = getExpectedFirstNode(**itNode, attVelocity);
orbitRecord.velocity[0] = getDoubleFromFirstNode(velocityNode, attX);
orbitRecord.velocity[1] = getDoubleFromFirstNode(velocityNode, attY);
orbitRecord.velocity[2] = getDoubleFromFirstNode(velocityNode, attZ);
//Add one orbits record
theOrbitRecords.push_back(orbitRecord);
}
//Parse the near range time (in seconds)
theNearRangeTime = getDoubleFromFirstNode(xmlRoot, "imageAnnotation/imageInformation/slantRangeTime");
//Parse the range sampling rate
theRangeSamplingRate = getDoubleFromFirstNode(xmlRoot, "generalAnnotation/productInformation/rangeSamplingRate");
//Parse the range resolution
theRangeResolution = getDoubleFromFirstNode(xmlRoot, "imageAnnotation/imageInformation/rangePixelSpacing");
//Parse the radar frequency
theRadarFrequency = getDoubleFromFirstNode(xmlRoot, "generalAnnotation/productInformation/radarFrequency");
//Parse azimuth time interval
const double azimuthTimeInterval = getDoubleFromFirstNode(xmlRoot, "imageAnnotation/imageInformation/azimuthTimeInterval");
#if defined(USE_BOOST_TIME)
theAzimuthTimeInterval = boost::posix_time::precise_duration(azimuthTimeInterval * 1000000.);
#else
theAzimuthTimeInterval = seconds(azimuthTimeInterval);
#endif
ossimNotify(ossimNotifyLevel_DEBUG) << "theAzimuthTimeInterval " << theAzimuthTimeInterval.total_microseconds() << "us\n";
// Now read burst records as well
xnodes.clear();
xmlDoc->findNodes("/product/swathTiming/burstList/burst",xnodes);
if(xnodes.empty())
{
BurstRecordType burstRecord;
burstRecord.startLine = 0;
burstRecord.azimuthStartTime = getTimeFromFirstNode(xmlRoot,"imageAnnotation/imageInformation/productFirstLineUtcTime");
ossimNotify(ossimNotifyLevel_DEBUG)<< burstRecord.azimuthStartTime<<'\n';
burstRecord.azimuthStopTime = getTimeFromFirstNode(xmlRoot,"imageAnnotation/imageInformation/productLastLineUtcTime");
burstRecord.endLine = getTextFromFirstNode(xmlRoot, "imageAnnotation/imageInformation/numberOfLines").toUInt16()-1;
burstRecord.startSample = 0;
burstRecord.endSample = getTextFromFirstNode(xmlRoot, "imageAnnotation/imageInformation/numberOfSamples").toUInt16()-1;;
theBurstRecords.push_back(burstRecord);
}
else
{
const unsigned int linesPerBurst = xmlRoot.findFirstNode("swathTiming/linesPerBurst")->getText().toUInt16();
const unsigned int samplesPerBurst = xmlRoot.findFirstNode("swathTiming/samplesPerBurst")->getText().toUInt16();
unsigned int burstId(0);
for(std::vector<ossimRefPtr<ossimXmlNode> >::iterator itNode = xnodes.begin(); itNode!=xnodes.end();++itNode,++burstId)
{
BurstRecordType burstRecord;
const ossimSarSensorModel::TimeType azTime = getTimeFromFirstNode(**itNode, attAzimuthTime);
// Scan firstValidSample to define the first valid sample and valid lines
ossimString const& s = getTextFromFirstNode(**itNode, attFirstValidSample);
long first_valid(0), last_valid(0);
bool begin_found(false), end_found(false);
long first_sample_valid(0), last_sample_valid(samplesPerBurst-1);
std::vector<ossimString> ssp = s.split(" ");
for (std::vector<ossimString>::const_iterator sIt = ssp.begin(), e = ssp.end()
; sIt != e && !end_found
; ++sIt
)
{
// Find valid lines
if(!begin_found)
{
if(*sIt!="-1")
{
begin_found = true;
}
else
{
++first_valid;
}
++last_valid;
}
else
{
if(!end_found && *sIt=="-1")
{
end_found = true;
--last_valid;
}
else
{
++last_valid;
}
}
// Find first valid samples
if(*sIt!="-1")
{
int Fvs = samplesPerBurst;
try
{
Fvs = std::stoi(*sIt);
}
catch( ... )
{
// Throw an execption
throw std::runtime_error("Failed to convert firstValidSample value.");
}
if (Fvs > first_sample_valid && Fvs < samplesPerBurst)
{
first_sample_valid = Fvs;
}
}
}
// Scan lastValidSample to define the last valid sample
ossimString const& sLast = getTextFromFirstNode(**itNode, attLastValidSample);
std::vector<ossimString> sspLast = sLast.split(" ");
for (std::vector<ossimString>::const_iterator sIt = sspLast.begin(), e = sspLast.end()
; sIt != e ; ++sIt)
{
// Last first valid samples
if(*sIt!="-1")
{
int Lvs = 0;
try
{
Lvs = std::stoi(*sIt);
}
catch( ... )
{
// Throw an execption
throw std::runtime_error("Failed to convert lastValidSample value.");
}
if (Lvs < last_sample_valid && Lvs > 0)
{
last_sample_valid = Lvs;
}
}
}
burstRecord.startLine = burstId*linesPerBurst + first_valid;
burstRecord.endLine = burstId*linesPerBurst + last_valid;
burstRecord.azimuthStartTime = azTime + (first_valid*theAzimuthTimeInterval);
burstRecord.azimuthStopTime = azTime + (last_valid*theAzimuthTimeInterval);
burstRecord.startSample = first_sample_valid;
burstRecord.endSample = last_sample_valid;
theBurstRecords.push_back(burstRecord);
}
}
if(isGRD())
{
readCoordinates(*xmlDoc,
"/product/coordinateConversion/coordinateConversionList/coordinateConversion",
attSr0, attSrgrCoefficients,
theSlantRangeToGroundRangeRecords);
readCoordinates(*xmlDoc,
"/product/coordinateConversion/coordinateConversionList/coordinateConversion",
attGr0, attGrsrCoefficients,
theGroundRangeToSlantRangeRecords);
}
xnodes.clear();
xmlDoc->findNodes("/product/geolocationGrid/geolocationGridPointList/geolocationGridPoint",xnodes);
for(std::vector<ossimRefPtr<ossimXmlNode> >::iterator itNode = xnodes.begin(); itNode!=xnodes.end();++itNode)
{
GCPRecordType gcpRecord;
// Retrieve acquisition time
gcpRecord.azimuthTime = getTimeFromFirstNode(**itNode, attAzimuthTime);
gcpRecord.slantRangeTime = getDoubleFromFirstNode(**itNode, attSlantRangeTime);
gcpRecord.imPt.x = getDoubleFromFirstNode(**itNode, attPixel);
// In TOPSAR products, GCPs are weird (they fall in black lines
// between burst. This code allows moving them to a valid area of
// the image.
if(theBurstRecords.size()>2)
{
ossimSarSensorModel::TimeType acqStart;
bool burstFound(false);
unsigned long acqStartLine(0);
for(std::vector<BurstRecordType>::reverse_iterator bIt = theBurstRecords.rbegin();bIt!=theBurstRecords.rend() && !burstFound;++bIt)
{
if(gcpRecord.azimuthTime >= bIt->azimuthStartTime && gcpRecord.azimuthTime < bIt->azimuthStopTime)
{
burstFound = true;
acqStart = bIt->azimuthStartTime;
acqStartLine = bIt->startLine;
}
}
if(!burstFound)
{
if(gcpRecord.azimuthTime < theBurstRecords.front().azimuthStartTime)
{
acqStart = theBurstRecords.front().azimuthStartTime;
acqStartLine = theBurstRecords.front().startLine;
}
else if (gcpRecord.azimuthTime >= theBurstRecords.front().azimuthStopTime)
{
acqStart = theBurstRecords.back().azimuthStartTime;
acqStartLine = theBurstRecords.back().startLine;
}
}
const DurationType timeSinceStart = gcpRecord.azimuthTime - acqStart;
gcpRecord.imPt.y= timeSinceStart/theAzimuthTimeInterval + acqStartLine;
ossimNotify(ossimNotifyLevel_DEBUG) << "timeSinceStart: " << timeSinceStart << " = " << gcpRecord.azimuthTime << " - " << acqStart << " (azTime-acqStart)"<< "\n";
ossimNotify(ossimNotifyLevel_DEBUG) << "imPt_y: " << gcpRecord.imPt.y << " = " << timeSinceStart.total_microseconds() << "/" << theAzimuthTimeInterval.total_microseconds() << "+" << acqStartLine << "\n";
}
else
{
gcpRecord.imPt.y = getDoubleFromFirstNode(**itNode, attLine);;
}
ossimGpt geoPoint;
gcpRecord.worldPt.lat = getDoubleFromFirstNode(**itNode, attLatitude);
gcpRecord.worldPt.lon = getDoubleFromFirstNode(**itNode, attLongitude);
gcpRecord.worldPt.hgt = getDoubleFromFirstNode(**itNode, attHeight);
theGCPRecords.push_back(gcpRecord);
}
this->optimizeTimeOffsetsFromGcps();
}
} // namespace ossimplugins
<commit_msg>WRG : Correction for Code review into Sentinel1SarSensorModel<commit_after>/*
* Copyright (C) 2005-2017 by Centre National d'Etudes Spatiales (CNES)
*
* This file is licensed under MIT license:
*
* 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 <ossimSentinel1SarSensorModel.h>
#include <ossim/base/ossimXmlDocument.h>
#include "ossim/ossimXmlTools.h"
namespace {// Anonymous namespace
const ossimString attAzimuthTime = "azimuthTime";
const ossimString attFirstValidSample = "firstValidSample";
const ossimString attLastValidSample = "lastValidSample";
const ossimString attGr0 = "gr0";
const ossimString attGrsrCoefficients = "grsrCoefficients";
const ossimString attHeight = "height";
const ossimString attLatitude = "latitude";
const ossimString attLine = "line";
const ossimString attLongitude = "longitude";
const ossimString attPixel = "pixel";
const ossimString attPosition = "position";
const ossimString attSlantRangeTime = "slantRangeTime";
const ossimString attSr0 = "sr0";
const ossimString attSrgrCoefficients = "srgrCoefficients";
const ossimString attTime = "time";
const ossimString attVelocity = "velocity";
const ossimString attX = "x";
const ossimString attY = "y";
const ossimString attZ = "z";
}// Anonymous namespace
#if defined(USE_BOOST_TIME)
using boost::posix_time::microseconds;
using boost::posix_time::seconds;
#else
using ossimplugins::time::microseconds;
using ossimplugins::time::seconds;
#endif
void ossimplugins::ossimSentinel1SarSensorModel::readCoordinates(
ossimXmlDocument const& xmlDoc, ossimString const& xpath,
ossimString const& rg0_xpath, ossimString const& coeffs_xpath,
std::vector<CoordinateConversionRecordType> & outputRecords)
{
std::vector<ossimRefPtr<ossimXmlNode> > xnodes;
xmlDoc.findNodes(xpath, xnodes);
for(std::vector<ossimRefPtr<ossimXmlNode> >::iterator itNode = xnodes.begin(); itNode!=xnodes.end();++itNode)
{
CoordinateConversionRecordType coordRecord;
coordRecord.azimuthTime = getTimeFromFirstNode(**itNode, attAzimuthTime);
coordRecord.rg0 = getDoubleFromFirstNode(**itNode, rg0_xpath);;
ossimString const& s = getTextFromFirstNode(**itNode, coeffs_xpath);
std::vector<ossimString> ssplit = s.split(" ");
if (ssplit.empty())
{
throw std::runtime_error(("The "+rg0_xpath+" record has an empty coef vector").string());
}
for (std::vector<ossimString>::const_iterator cIt = ssplit.begin(), e = ssplit.end()
; cIt != e
; ++cIt
)
{
coordRecord.coefs.push_back(cIt->toDouble());
}
assert(!coordRecord.coefs.empty()&&"The rg0 record has empty coefs vector.");
outputRecords.push_back(coordRecord);
}
}
namespace ossimplugins
{
void ossimSentinel1SarSensorModel::readAnnotationFile(const std::string & annotationXml)
{
ossimRefPtr<ossimXmlDocument> xmlDoc = new ossimXmlDocument(annotationXml);
const ossimXmlNode & xmlRoot = *xmlDoc->getRoot();
//Parse specific metadata for Sentinel1
//TODO add as members to the Sentinel1SarSensorModel
const std::string & product_type = getTextFromFirstNode(xmlRoot, "adsHeader/productType");
const std::string & mode = getTextFromFirstNode(xmlRoot, "adsHeader/mode");
const std::string & swath = getTextFromFirstNode(xmlRoot, "adsHeader/swath");
const std::string & polarisation = getTextFromFirstNode(xmlRoot, "adsHeader/polarisation");
theProductType = ProductType(product_type);
// First, lookup position/velocity records
std::vector<ossimRefPtr<ossimXmlNode> > xnodes;
xmlDoc->findNodes("/product/generalAnnotation/orbitList/orbit",xnodes);
//TODO uncomment and adapt following code from s1_inverse to fill
//SarSensorModel structure
for(std::vector<ossimRefPtr<ossimXmlNode> >::iterator itNode = xnodes.begin(); itNode!=xnodes.end();++itNode)
{
OrbitRecordType orbitRecord;
// Retrieve acquisition time
orbitRecord.azimuthTime = getTimeFromFirstNode(**itNode, attTime);
// Retrieve ECEF position
ossimXmlNode const& positionNode = getExpectedFirstNode(**itNode, attPosition);
orbitRecord.position[0] = getDoubleFromFirstNode(positionNode, attX);
orbitRecord.position[1] = getDoubleFromFirstNode(positionNode, attY);
orbitRecord.position[2] = getDoubleFromFirstNode(positionNode, attZ);
// Retrieve ECEF velocity
ossimXmlNode const& velocityNode = getExpectedFirstNode(**itNode, attVelocity);
orbitRecord.velocity[0] = getDoubleFromFirstNode(velocityNode, attX);
orbitRecord.velocity[1] = getDoubleFromFirstNode(velocityNode, attY);
orbitRecord.velocity[2] = getDoubleFromFirstNode(velocityNode, attZ);
//Add one orbits record
theOrbitRecords.push_back(orbitRecord);
}
//Parse the near range time (in seconds)
theNearRangeTime = getDoubleFromFirstNode(xmlRoot, "imageAnnotation/imageInformation/slantRangeTime");
//Parse the range sampling rate
theRangeSamplingRate = getDoubleFromFirstNode(xmlRoot, "generalAnnotation/productInformation/rangeSamplingRate");
//Parse the range resolution
theRangeResolution = getDoubleFromFirstNode(xmlRoot, "imageAnnotation/imageInformation/rangePixelSpacing");
//Parse the radar frequency
theRadarFrequency = getDoubleFromFirstNode(xmlRoot, "generalAnnotation/productInformation/radarFrequency");
//Parse azimuth time interval
const double azimuthTimeInterval = getDoubleFromFirstNode(xmlRoot, "imageAnnotation/imageInformation/azimuthTimeInterval");
#if defined(USE_BOOST_TIME)
theAzimuthTimeInterval = boost::posix_time::precise_duration(azimuthTimeInterval * 1000000.);
#else
theAzimuthTimeInterval = seconds(azimuthTimeInterval);
#endif
ossimNotify(ossimNotifyLevel_DEBUG) << "theAzimuthTimeInterval " << theAzimuthTimeInterval.total_microseconds() << "us\n";
// Now read burst records as well
xnodes.clear();
xmlDoc->findNodes("/product/swathTiming/burstList/burst",xnodes);
if(xnodes.empty())
{
BurstRecordType burstRecord;
burstRecord.startLine = 0;
burstRecord.azimuthStartTime = getTimeFromFirstNode(xmlRoot,"imageAnnotation/imageInformation/productFirstLineUtcTime");
ossimNotify(ossimNotifyLevel_DEBUG)<< burstRecord.azimuthStartTime<<'\n';
burstRecord.azimuthStopTime = getTimeFromFirstNode(xmlRoot,"imageAnnotation/imageInformation/productLastLineUtcTime");
burstRecord.endLine = getTextFromFirstNode(xmlRoot, "imageAnnotation/imageInformation/numberOfLines").toUInt16()-1;
burstRecord.startSample = 0;
burstRecord.endSample = getTextFromFirstNode(xmlRoot, "imageAnnotation/imageInformation/numberOfSamples").toUInt16()-1;;
theBurstRecords.push_back(burstRecord);
}
else
{
const unsigned int linesPerBurst = xmlRoot.findFirstNode("swathTiming/linesPerBurst")->getText().toUInt16();
const unsigned int samplesPerBurst = xmlRoot.findFirstNode("swathTiming/samplesPerBurst")->getText().toUInt16();
unsigned int burstId(0);
for(std::vector<ossimRefPtr<ossimXmlNode> >::iterator itNode = xnodes.begin(); itNode!=xnodes.end();++itNode,++burstId)
{
BurstRecordType burstRecord;
const ossimSarSensorModel::TimeType azTime = getTimeFromFirstNode(**itNode, attAzimuthTime);
// Scan firstValidSample to define the first valid sample and valid lines
ossimString const& s = getTextFromFirstNode(**itNode, attFirstValidSample);
long first_valid(0), last_valid(0);
bool begin_found(false), end_found(false);
long first_sample_valid(0), last_sample_valid(samplesPerBurst-1);
std::vector<ossimString> ssp = s.split(" ");
for (std::vector<ossimString>::const_iterator sIt = ssp.begin(), e = ssp.end()
; sIt != e && !end_found
; ++sIt
)
{
// Find valid lines
if(!begin_found)
{
if(*sIt!="-1")
{
begin_found = true;
}
else
{
++first_valid;
}
++last_valid;
}
else
{
if(!end_found && *sIt=="-1")
{
end_found = true;
--last_valid;
}
else
{
++last_valid;
}
}
// Find first valid samples
if(*sIt!="-1")
{
int Fvs = samplesPerBurst;
try
{
Fvs = std::stoi(*sIt);
}
catch( ... )
{
// Throw an execption
throw std::runtime_error("Failed to convert firstValidSample value.");
}
if (Fvs > first_sample_valid && Fvs < samplesPerBurst)
{
first_sample_valid = Fvs;
}
}
}
// Scan lastValidSample to define the last valid sample
ossimString const& sLast = getTextFromFirstNode(**itNode, attLastValidSample);
std::vector<ossimString> sspLast = sLast.split(" ");
for (auto const& token : sspLast)
{
// Last first valid samples
if(token != "-1")
{
int Lvs = 0;
try
{
Lvs = std::stoi(token);
}
catch( ... )
{
// Throw an execption
throw std::runtime_error("Failed to convert lastValidSample value.");
}
if (Lvs < last_sample_valid && Lvs > 0)
{
last_sample_valid = Lvs;
}
}
}
burstRecord.startLine = burstId*linesPerBurst + first_valid;
burstRecord.endLine = burstId*linesPerBurst + last_valid;
burstRecord.azimuthStartTime = azTime + (first_valid*theAzimuthTimeInterval);
burstRecord.azimuthStopTime = azTime + (last_valid*theAzimuthTimeInterval);
burstRecord.startSample = first_sample_valid;
burstRecord.endSample = last_sample_valid;
theBurstRecords.push_back(burstRecord);
}
}
if(isGRD())
{
readCoordinates(*xmlDoc,
"/product/coordinateConversion/coordinateConversionList/coordinateConversion",
attSr0, attSrgrCoefficients,
theSlantRangeToGroundRangeRecords);
readCoordinates(*xmlDoc,
"/product/coordinateConversion/coordinateConversionList/coordinateConversion",
attGr0, attGrsrCoefficients,
theGroundRangeToSlantRangeRecords);
}
xnodes.clear();
xmlDoc->findNodes("/product/geolocationGrid/geolocationGridPointList/geolocationGridPoint",xnodes);
for(std::vector<ossimRefPtr<ossimXmlNode> >::iterator itNode = xnodes.begin(); itNode!=xnodes.end();++itNode)
{
GCPRecordType gcpRecord;
// Retrieve acquisition time
gcpRecord.azimuthTime = getTimeFromFirstNode(**itNode, attAzimuthTime);
gcpRecord.slantRangeTime = getDoubleFromFirstNode(**itNode, attSlantRangeTime);
gcpRecord.imPt.x = getDoubleFromFirstNode(**itNode, attPixel);
// In TOPSAR products, GCPs are weird (they fall in black lines
// between burst. This code allows moving them to a valid area of
// the image.
if(theBurstRecords.size()>2)
{
ossimSarSensorModel::TimeType acqStart;
bool burstFound(false);
unsigned long acqStartLine(0);
for(std::vector<BurstRecordType>::reverse_iterator bIt = theBurstRecords.rbegin();bIt!=theBurstRecords.rend() && !burstFound;++bIt)
{
if(gcpRecord.azimuthTime >= bIt->azimuthStartTime && gcpRecord.azimuthTime < bIt->azimuthStopTime)
{
burstFound = true;
acqStart = bIt->azimuthStartTime;
acqStartLine = bIt->startLine;
}
}
if(!burstFound)
{
if(gcpRecord.azimuthTime < theBurstRecords.front().azimuthStartTime)
{
acqStart = theBurstRecords.front().azimuthStartTime;
acqStartLine = theBurstRecords.front().startLine;
}
else if (gcpRecord.azimuthTime >= theBurstRecords.front().azimuthStopTime)
{
acqStart = theBurstRecords.back().azimuthStartTime;
acqStartLine = theBurstRecords.back().startLine;
}
}
const DurationType timeSinceStart = gcpRecord.azimuthTime - acqStart;
gcpRecord.imPt.y= timeSinceStart/theAzimuthTimeInterval + acqStartLine;
ossimNotify(ossimNotifyLevel_DEBUG) << "timeSinceStart: " << timeSinceStart << " = " << gcpRecord.azimuthTime << " - " << acqStart << " (azTime-acqStart)"<< "\n";
ossimNotify(ossimNotifyLevel_DEBUG) << "imPt_y: " << gcpRecord.imPt.y << " = " << timeSinceStart.total_microseconds() << "/" << theAzimuthTimeInterval.total_microseconds() << "+" << acqStartLine << "\n";
}
else
{
gcpRecord.imPt.y = getDoubleFromFirstNode(**itNode, attLine);;
}
ossimGpt geoPoint;
gcpRecord.worldPt.lat = getDoubleFromFirstNode(**itNode, attLatitude);
gcpRecord.worldPt.lon = getDoubleFromFirstNode(**itNode, attLongitude);
gcpRecord.worldPt.hgt = getDoubleFromFirstNode(**itNode, attHeight);
theGCPRecords.push_back(gcpRecord);
}
this->optimizeTimeOffsetsFromGcps();
}
} // namespace ossimplugins
<|endoftext|> |
<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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 <configuration.hpp>
#include <CommandLine.hpp>
#include <Kernels.hpp>
#include <Memory.hpp>
#include <Pipeline.hpp>
int main(int argc, char * argv[]) {
// Command line options
Options options;
DeviceOptions deviceOptions;
DataOptions dataOptions;
GeneratorOptions generatorOptions;
// Memory
HostMemory hostMemory;
DeviceMemory deviceMemory;
// OpenCL kernels
OpenCLRunTime openclRunTime;
KernelConfigurations kernelConfigurations;
Kernels kernels;
KernelRunTimeConfigurations kernelRunTimeConfigurations;
// Timers
Timers timers;
// Observation
AstroData::Observation observation;
// Process command line arguments
isa::utils::ArgumentList args(argc, argv);
try {
processCommandLineOptions(args, options, deviceOptions, dataOptions, kernelConfigurations, generatorOptions,
observation);
} catch ( std::exception & err ) {
return 1;
}
// Load or generate input data
try {
if ( dataOptions.dataLOFAR || dataOptions.dataSIGPROC || dataOptions.dataPSRDADA ) {
loadInput(observation, deviceOptions, dataOptions, hostMemory, timers);
} else {
hostMemory.input.resize(observation.getNrBeams());
for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) {
// TODO: if there are multiple synthesized beams, the generated data should take this into account
hostMemory.input.at(beam) = new std::vector<std::vector<inputDataType> *>(observation.getNrBatches());
AstroData::generateSinglePulse(generatorOptions.width, generatorOptions.DM, observation,
deviceOptions.padding.at(deviceOptions.deviceName),
*(hostMemory.input.at(beam)), inputBits, generatorOptions.random);
}
}
} catch ( std::exception & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Print message with observation and search information
if ( options.print) {
std::cout << "Device: " << deviceOptions.deviceName << "(" + std::to_string(deviceOptions.platformID) + ", ";
std::cout << std::to_string(deviceOptions.deviceID) + ")" << std::endl;
std::cout << "Padding: " << deviceOptions.padding[deviceOptions.deviceName] << " bytes" << std::endl;
std::cout << std::endl;
std::cout << "Beams: " << observation.getNrBeams() << std::endl;
std::cout << "Synthesized Beams: " << observation.getNrSynthesizedBeams() << std::endl;
std::cout << "Batches: " << observation.getNrBatches() << std::endl;
std::cout << "Samples: " << observation.getNrSamplesPerBatch() << std::endl;
std::cout << "Sampling time: " << observation.getSamplingTime() << std::endl;
std::cout << "Frequency range: " << observation.getMinFreq() << " MHz, " << observation.getMaxFreq() << " MHz";
std::cout << std::endl;
std::cout << "Subbands: " << observation.getNrSubbands() << " (" << observation.getSubbandBandwidth() << " MHz)";
std::cout << std::endl;
std::cout << "Channels: " << observation.getNrChannels() << " (" << observation.getChannelBandwidth() << " MHz)";
std::cout << std::endl;
std::cout << "Zapped Channels: " << observation.getNrZappedChannels() << std::endl;
std::cout << "Integration steps: " << hostMemory.integrationSteps.size() << std::endl;
if ( options.subbandDedispersion ) {
std::cout << "Subbanding DMs: " << observation.getNrDMs(true) << " (" << observation.getFirstDM(true) << ", ";
std::cout << observation.getFirstDM(true) + ((observation.getNrDMs(true) - 1) * observation.getDMStep(true));
std::cout << ")" << std::endl;
}
std::cout << "DMs: " << observation.getNrDMs() << " (" << observation.getFirstDM() << ", ";
std::cout << observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()) << ")";
std::cout << std::endl;
std::cout << std::endl;
}
// Initialize OpenCL
openclRunTime.context = new cl::Context();
openclRunTime.platforms = new std::vector<cl::Platform>();
openclRunTime.devices = new std::vector<cl::Device>();
openclRunTime.queues = new std::vector<std::vector<cl::CommandQueue>>();
try {
isa::OpenCL::initializeOpenCL(deviceOptions.platformID, 1, openclRunTime.platforms, openclRunTime.context,
openclRunTime.devices, openclRunTime.queues);
} catch ( isa::OpenCL::OpenCLError & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Memory allocation
allocateHostMemory(observation, options, deviceOptions, kernelConfigurations, hostMemory);
if ( observation.getNrDelayBatches() > observation.getNrBatches() ) {
std::cerr << "Not enough input batches for the specified search." << std::endl;
return 1;
}
try {
allocateDeviceMemory(openclRunTime, options, deviceOptions, hostMemory, deviceMemory);
} catch ( cl::Error & err ) {
std::cerr << "Memory error: " << err.what() << " " << err.err() << std::endl;
return 1;
}
// Generate OpenCL kernels
try {
generateOpenCLKernels(openclRunTime, observation, options, deviceOptions, kernelConfigurations, hostMemory,
deviceMemory, kernels);
} catch ( std::exception & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Generate run time configurations for the OpenCL kernels
generateOpenCLRunTimeConfigurations(observation, options, deviceOptions, kernelConfigurations, hostMemory,
kernelRunTimeConfigurations);
// Search loop
pipeline(openclRunTime, observation, options, deviceOptions, dataOptions, timers, kernels, kernelConfigurations,
kernelRunTimeConfigurations, hostMemory, deviceMemory);
// Store performance statistics before shutting down
std::ofstream outputStats;
outputStats.open(dataOptions.outputFile + ".stats");
outputStats << std::fixed << std::setprecision(6);
outputStats << "# nrDMs" << std::endl;
if ( options.subbandDedispersion ) {
outputStats << observation.getNrDMs(true) * observation.getNrDMs() << std::endl;
} else {
outputStats << observation.getNrDMs() << std::endl;
}
outputStats << "# timers.inputLoad" << std::endl;
outputStats << timers.inputLoad.getTotalTime() << std::endl;
outputStats << "# timers.search" << std::endl;
outputStats << timers.search.getTotalTime() << std::endl;
outputStats << "# inputHandlingTotal inputHandlingAvg err" << std::endl;
outputStats << timers.inputHandling.getTotalTime() << " " << timers.inputHandling.getAverageTime() << " ";
outputStats << timers.inputHandling.getStandardDeviation() << std::endl;
outputStats << "# inputCopyTotal inputCopyAvg err" << std::endl;
outputStats << timers.inputCopy.getTotalTime() << " " << timers.inputCopy.getAverageTime() << " ";
outputStats << timers.inputCopy.getStandardDeviation() << std::endl;
if ( ! options.subbandDedispersion ) {
outputStats << "# dedispersionSingleStepTotal dedispersionSingleStepAvg err" << std::endl;
outputStats << timers.dedispersionSingleStep.getTotalTime() << " ";
outputStats << timers.dedispersionSingleStep.getAverageTime() << " ";
outputStats << timers.dedispersionSingleStep.getStandardDeviation() << std::endl;
} else {
outputStats << "# dedispersionStepOneTotal dedispersionStepOneAvg err" << std::endl;
outputStats << timers.dedispersionStepOne.getTotalTime() << " ";
outputStats << timers.dedispersionStepOne.getAverageTime() << " ";
outputStats << timers.dedispersionStepOne.getStandardDeviation() << std::endl;
outputStats << "# dedispersionStepTwoTotal dedispersionStepTwoAvg err" << std::endl;
outputStats << timers.dedispersionStepTwo.getTotalTime() << " ";
outputStats << timers.dedispersionStepTwo.getAverageTime() << " ";
outputStats << timers.dedispersionStepTwo.getStandardDeviation() << std::endl;
}
outputStats << "# integrationTotal integrationAvg err" << std::endl;
outputStats << timers.integration.getTotalTime() << " " << timers.integration.getAverageTime() << " ";
outputStats << timers.integration.getStandardDeviation() << std::endl;
outputStats << "# snrTotal snrAvg err" << std::endl;
outputStats << timers.snr.getTotalTime() << " " << timers.snr.getAverageTime() << " ";
outputStats << timers.snr.getStandardDeviation() << std::endl;
outputStats << "# outputCopyTotal outputCopyAvg err" << std::endl;
outputStats << timers.outputCopy.getTotalTime() << " " << timers.outputCopy.getAverageTime() << " ";
outputStats << timers.outputCopy.getStandardDeviation() << std::endl;
outputStats << "# triggerTimeTotal triggerTimeAvg err" << std::endl;
outputStats << timers.trigger.getTotalTime() << " " << timers.trigger.getAverageTime() << " ";
outputStats << timers.trigger.getStandardDeviation() << std::endl;
outputStats.close();
return 0;
}
<commit_msg>Including some preliminary operations that are necessary for loading and generating.<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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 <configuration.hpp>
#include <CommandLine.hpp>
#include <Kernels.hpp>
#include <Memory.hpp>
#include <Pipeline.hpp>
int main(int argc, char * argv[]) {
// Command line options
Options options;
DeviceOptions deviceOptions;
DataOptions dataOptions;
GeneratorOptions generatorOptions;
// Memory
HostMemory hostMemory;
DeviceMemory deviceMemory;
// OpenCL kernels
OpenCLRunTime openclRunTime;
KernelConfigurations kernelConfigurations;
Kernels kernels;
KernelRunTimeConfigurations kernelRunTimeConfigurations;
// Timers
Timers timers;
// Observation
AstroData::Observation observation;
// Process command line arguments
isa::utils::ArgumentList args(argc, argv);
try {
processCommandLineOptions(args, options, deviceOptions, dataOptions, kernelConfigurations, generatorOptions,
observation);
} catch ( std::exception & err ) {
return 1;
}
// Load or generate input data
try {
hostMemory.zappedChannels.resize(observation.getNrChannels(deviceOptions.padding.at(deviceOptions.deviceName)
/ sizeof(unsigned int)));
try {
AstroData::readZappedChannels(observation, dataOptions.channelsFile, hostMemory.zappedChannels);
AstroData::readIntegrationSteps(observation, dataOptions.integrationFile, hostMemory.integrationSteps);
} catch ( AstroData::FileError & err ) {
std::cerr << err.what() << std::endl;
throw;
}
hostMemory.input.resize(observation.getNrBeams());
if ( dataOptions.dataLOFAR || dataOptions.dataSIGPROC || dataOptions.dataPSRDADA ) {
loadInput(observation, deviceOptions, dataOptions, hostMemory, timers);
} else {
for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) {
// TODO: if there are multiple synthesized beams, the generated data should take this into account
hostMemory.input.at(beam) = new std::vector<std::vector<inputDataType> *>(observation.getNrBatches());
AstroData::generateSinglePulse(generatorOptions.width, generatorOptions.DM, observation,
deviceOptions.padding.at(deviceOptions.deviceName),
*(hostMemory.input.at(beam)), inputBits, generatorOptions.random);
}
}
} catch ( std::exception & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Print message with observation and search information
if ( options.print) {
std::cout << "Device: " << deviceOptions.deviceName << "(" + std::to_string(deviceOptions.platformID) + ", ";
std::cout << std::to_string(deviceOptions.deviceID) + ")" << std::endl;
std::cout << "Padding: " << deviceOptions.padding[deviceOptions.deviceName] << " bytes" << std::endl;
std::cout << std::endl;
std::cout << "Beams: " << observation.getNrBeams() << std::endl;
std::cout << "Synthesized Beams: " << observation.getNrSynthesizedBeams() << std::endl;
std::cout << "Batches: " << observation.getNrBatches() << std::endl;
std::cout << "Samples: " << observation.getNrSamplesPerBatch() << std::endl;
std::cout << "Sampling time: " << observation.getSamplingTime() << std::endl;
std::cout << "Frequency range: " << observation.getMinFreq() << " MHz, " << observation.getMaxFreq() << " MHz";
std::cout << std::endl;
std::cout << "Subbands: " << observation.getNrSubbands() << " (" << observation.getSubbandBandwidth() << " MHz)";
std::cout << std::endl;
std::cout << "Channels: " << observation.getNrChannels() << " (" << observation.getChannelBandwidth() << " MHz)";
std::cout << std::endl;
std::cout << "Zapped Channels: " << observation.getNrZappedChannels() << std::endl;
std::cout << "Integration steps: " << hostMemory.integrationSteps.size() << std::endl;
if ( options.subbandDedispersion ) {
std::cout << "Subbanding DMs: " << observation.getNrDMs(true) << " (" << observation.getFirstDM(true) << ", ";
std::cout << observation.getFirstDM(true) + ((observation.getNrDMs(true) - 1) * observation.getDMStep(true));
std::cout << ")" << std::endl;
}
std::cout << "DMs: " << observation.getNrDMs() << " (" << observation.getFirstDM() << ", ";
std::cout << observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()) << ")";
std::cout << std::endl;
std::cout << std::endl;
}
// Initialize OpenCL
openclRunTime.context = new cl::Context();
openclRunTime.platforms = new std::vector<cl::Platform>();
openclRunTime.devices = new std::vector<cl::Device>();
openclRunTime.queues = new std::vector<std::vector<cl::CommandQueue>>();
try {
isa::OpenCL::initializeOpenCL(deviceOptions.platformID, 1, openclRunTime.platforms, openclRunTime.context,
openclRunTime.devices, openclRunTime.queues);
} catch ( isa::OpenCL::OpenCLError & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Memory allocation
allocateHostMemory(observation, options, deviceOptions, kernelConfigurations, hostMemory);
if ( observation.getNrDelayBatches() > observation.getNrBatches() ) {
std::cerr << "Not enough input batches for the specified search." << std::endl;
return 1;
}
try {
allocateDeviceMemory(openclRunTime, options, deviceOptions, hostMemory, deviceMemory);
} catch ( cl::Error & err ) {
std::cerr << "Memory error: " << err.what() << " " << err.err() << std::endl;
return 1;
}
// Generate OpenCL kernels
try {
generateOpenCLKernels(openclRunTime, observation, options, deviceOptions, kernelConfigurations, hostMemory,
deviceMemory, kernels);
} catch ( std::exception & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Generate run time configurations for the OpenCL kernels
generateOpenCLRunTimeConfigurations(observation, options, deviceOptions, kernelConfigurations, hostMemory,
kernelRunTimeConfigurations);
// Search loop
pipeline(openclRunTime, observation, options, deviceOptions, dataOptions, timers, kernels, kernelConfigurations,
kernelRunTimeConfigurations, hostMemory, deviceMemory);
// Store performance statistics before shutting down
std::ofstream outputStats;
outputStats.open(dataOptions.outputFile + ".stats");
outputStats << std::fixed << std::setprecision(6);
outputStats << "# nrDMs" << std::endl;
if ( options.subbandDedispersion ) {
outputStats << observation.getNrDMs(true) * observation.getNrDMs() << std::endl;
} else {
outputStats << observation.getNrDMs() << std::endl;
}
outputStats << "# timers.inputLoad" << std::endl;
outputStats << timers.inputLoad.getTotalTime() << std::endl;
outputStats << "# timers.search" << std::endl;
outputStats << timers.search.getTotalTime() << std::endl;
outputStats << "# inputHandlingTotal inputHandlingAvg err" << std::endl;
outputStats << timers.inputHandling.getTotalTime() << " " << timers.inputHandling.getAverageTime() << " ";
outputStats << timers.inputHandling.getStandardDeviation() << std::endl;
outputStats << "# inputCopyTotal inputCopyAvg err" << std::endl;
outputStats << timers.inputCopy.getTotalTime() << " " << timers.inputCopy.getAverageTime() << " ";
outputStats << timers.inputCopy.getStandardDeviation() << std::endl;
if ( ! options.subbandDedispersion ) {
outputStats << "# dedispersionSingleStepTotal dedispersionSingleStepAvg err" << std::endl;
outputStats << timers.dedispersionSingleStep.getTotalTime() << " ";
outputStats << timers.dedispersionSingleStep.getAverageTime() << " ";
outputStats << timers.dedispersionSingleStep.getStandardDeviation() << std::endl;
} else {
outputStats << "# dedispersionStepOneTotal dedispersionStepOneAvg err" << std::endl;
outputStats << timers.dedispersionStepOne.getTotalTime() << " ";
outputStats << timers.dedispersionStepOne.getAverageTime() << " ";
outputStats << timers.dedispersionStepOne.getStandardDeviation() << std::endl;
outputStats << "# dedispersionStepTwoTotal dedispersionStepTwoAvg err" << std::endl;
outputStats << timers.dedispersionStepTwo.getTotalTime() << " ";
outputStats << timers.dedispersionStepTwo.getAverageTime() << " ";
outputStats << timers.dedispersionStepTwo.getStandardDeviation() << std::endl;
}
outputStats << "# integrationTotal integrationAvg err" << std::endl;
outputStats << timers.integration.getTotalTime() << " " << timers.integration.getAverageTime() << " ";
outputStats << timers.integration.getStandardDeviation() << std::endl;
outputStats << "# snrTotal snrAvg err" << std::endl;
outputStats << timers.snr.getTotalTime() << " " << timers.snr.getAverageTime() << " ";
outputStats << timers.snr.getStandardDeviation() << std::endl;
outputStats << "# outputCopyTotal outputCopyAvg err" << std::endl;
outputStats << timers.outputCopy.getTotalTime() << " " << timers.outputCopy.getAverageTime() << " ";
outputStats << timers.outputCopy.getStandardDeviation() << std::endl;
outputStats << "# triggerTimeTotal triggerTimeAvg err" << std::endl;
outputStats << timers.trigger.getTotalTime() << " " << timers.trigger.getAverageTime() << " ";
outputStats << timers.trigger.getStandardDeviation() << std::endl;
outputStats.close();
return 0;
}
<|endoftext|> |
<commit_before>#include "FileStatusColumn.h"
#include <Catalog.h>
#include <ControlLook.h>
#include <StringForRate.h>
#include "Utils.h"
#include "stdio.h"
#define kTEXT_MARGIN 8
#define kSPACE_TEXT 0
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "FileStatusColumn"
//=====================================================================
FileStatusField::FileStatusField(FileStatus status)
:fWidth(0),
fString(""),
fClippedString("")
{
SetFileStatus(status);
SetFilePercentage(0);
}
void
FileStatusField::SetFileStatus(FileStatus status)
{
if(status!=fStatus) {
fWidth = 0;
fClippedString.SetTo("");
fStatus=status;
switch(fStatus){
case NO_ENCLOSURE:
fOriginalStatus.SetTo(" ");
break;
case NEW:
fOriginalStatus.SetTo(B_TRANSLATE("new"));
break;
case NOT_DOWNLOADED:
fOriginalStatus.SetTo(B_TRANSLATE("not downloaded"));
break;
case DOWNLOADED:
fOriginalStatus.SetTo(B_TRANSLATE("downloaded"));
break;
case ERROR:
fOriginalStatus.SetTo(B_TRANSLATE("error"));
break;
case STOPPED:
fOriginalStatus.SetTo(B_TRANSLATE("stopped"));
break;
case NOT_FOUND:
fOriginalStatus.SetTo(B_TRANSLATE("not found"));
break;
case CANT_CONNECT:
fOriginalStatus.SetTo(B_TRANSLATE("can't connect"));
break;
case DOWNLOADING:
fOriginalStatus.SetTo(B_TRANSLATE("downloading"));
break;
case ENQUEQUED:
fOriginalStatus.SetTo(B_TRANSLATE("enquequed"));
break;
case CONNECTING:
fOriginalStatus.SetTo(B_TRANSLATE("connecting"));
break;
default:
fOriginalStatus.SetTo(B_TRANSLATE("error"));
break;
}
fString=fOriginalStatus;
if(fStatus==STOPPED){
//pervert game
int perv=fPercentage;
SetFilePercentage(0);
SetFilePercentage(perv);
}
}
}
void
FileStatusField::SetFilePercentage(int per,float speed)
{
if (fPercentage == per)
return;
if (per < 0)
per = 0;
fWidth = 0;
fClippedString.SetTo("");
fPercentage=per;
if(fStatus == STOPPED || fStatus == DOWNLOADING) {
BString sp;
sp << per << "% ";
if(speed>0 && fStatus == DOWNLOADING)
{
char rateString[32];
sp << string_for_rate(speed, rateString, sizeof(rateString)) << " ";
}
sp << fOriginalStatus;
fString = sp;
}
}
//--------------------------------------------------------------------
void FileStatusField::SetString(const char* val)
{
fString = val;
fClippedString = "";
fWidth = 0;
}
//--------------------------------------------------------------------
const char* FileStatusField::String() const
{
return fString.String();
}
//--------------------------------------------------------------------
void FileStatusField::SetWidth(float width)
{
fWidth = width;
}
//--------------------------------------------------------------------
float FileStatusField::Width()
{
return fWidth;
}
//--------------------------------------------------------------------
void FileStatusField::SetClippedString(const char* val)
{
fClippedString = val;
}
//--------------------------------------------------------------------
const char* FileStatusField::ClippedString()
{
return fClippedString.String();
}
//=====================================================================
FileStatusColumn::FileStatusColumn(const char* title, float width, float minWidth,
float maxWidth, uint32 truncate, alignment align)
:BTitledColumn(title, width, minWidth, maxWidth, align),
fTruncate(truncate)
{
}
//--------------------------------------------------------------------
void FileStatusColumn::DrawField(BField* _field, BRect rect, BView* parent)
{
FileStatusField* field = static_cast<FileStatusField*>(_field);
float width = rect.Width() - (2 * kTEXT_MARGIN);
float basePoint = 0;
if(field->GetFileStatus() == STOPPED ||
field->GetFileStatus() == DOWNLOADING )
{
basePoint = 100 + kSPACE_TEXT;
}
if (width - basePoint != field->Width())
{
BString out_string(field->String());
parent->TruncateString(&out_string, fTruncate, width + 2 - basePoint);
field->SetClippedString(out_string.String());
field->SetWidth(width - basePoint);
}
if(basePoint>0){
DrawBar(parent,rect,field->GetPercentage());
}
rect.left +=basePoint;
DrawString(field->ClippedString(), parent, rect);
}
void
FileStatusColumn::DrawBar(BView* parent,BRect rect,int number)
{
parent->PushState();
//parent->SetDrawingMode( B_OP_ALPHA );
//parent->SetBlendingMode( B_PIXEL_ALPHA, B_ALPHA_OVERLAY);
BRect graphRect(rect);
graphRect.left += 2;
graphRect.right = graphRect.left + 99 + 1;
float offsetY = (graphRect.Height() - 12) / 2;
graphRect.top += offsetY;
graphRect.bottom -= offsetY;
number = number > 0 ? number : 1;
be_control_look->DrawStatusBar(parent, graphRect, graphRect,
ui_color(B_LIST_BACKGROUND_COLOR), ui_color(B_STATUS_BAR_COLOR),
graphRect.left + number);
parent->PopState();
}
//--------------------------------------------------------------------
int FileStatusColumn::CompareFields(BField* field1, BField* field2)
{
return(ICompare(((FileStatusField*)field1)->String(),
(((FileStatusField*)field2)->String())));
}
//--------------------------------------------------------------------
bool FileStatusColumn::AcceptsField(const BField *field) const
{
return static_cast<bool>(dynamic_cast<const FileStatusField*>(field));
}
<commit_msg>Fix download/stop status column<commit_after>#include "FileStatusColumn.h"
#include <Catalog.h>
#include <ControlLook.h>
#include <StringForRate.h>
#include "Utils.h"
#include "stdio.h"
#define kTEXT_MARGIN 8
#define kSPACE_TEXT 0
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "FileStatusColumn"
//=====================================================================
FileStatusField::FileStatusField(FileStatus status)
:fWidth(0),
fString(""),
fClippedString("")
{
SetFileStatus(status);
SetFilePercentage(0);
}
void
FileStatusField::SetFileStatus(FileStatus status)
{
if(status!=fStatus) {
fWidth = 0;
fClippedString.SetTo("");
fStatus=status;
switch(fStatus){
case NO_ENCLOSURE:
fOriginalStatus.SetTo(" ");
break;
case NEW:
fOriginalStatus.SetTo(B_TRANSLATE("new"));
break;
case NOT_DOWNLOADED:
fOriginalStatus.SetTo(B_TRANSLATE("not downloaded"));
break;
case DOWNLOADED:
fOriginalStatus.SetTo(B_TRANSLATE("downloaded"));
break;
case ERROR:
fOriginalStatus.SetTo(B_TRANSLATE("error"));
break;
case STOPPED:
fOriginalStatus.SetTo(B_TRANSLATE("stopped"));
break;
case NOT_FOUND:
fOriginalStatus.SetTo(B_TRANSLATE("not found"));
break;
case CANT_CONNECT:
fOriginalStatus.SetTo(B_TRANSLATE("can't connect"));
break;
case DOWNLOADING:
fOriginalStatus.SetTo(B_TRANSLATE("downloading"));
break;
case ENQUEQUED:
fOriginalStatus.SetTo(B_TRANSLATE("enquequed"));
break;
case CONNECTING:
fOriginalStatus.SetTo(B_TRANSLATE("connecting"));
break;
default:
fOriginalStatus.SetTo(B_TRANSLATE("error"));
break;
}
fString=fOriginalStatus;
if(fStatus==STOPPED){
//pervert game
int perv=fPercentage;
SetFilePercentage(0);
SetFilePercentage(perv);
}
}
}
void
FileStatusField::SetFilePercentage(int per,float speed)
{
if (fPercentage == per)
return;
if (per < 0)
per = 0;
fWidth = 0;
fClippedString.SetTo("");
fPercentage=per;
if(fStatus == STOPPED || fStatus == DOWNLOADING) {
BString sp;
sp << per << "% ";
if(speed>0 && fStatus == DOWNLOADING)
{
char rateString[32];
sp << "- " << string_for_rate(speed, rateString, sizeof(rateString));
}
if (fStatus == STOPPED)
sp << fOriginalStatus;
fString = sp;
}
}
//--------------------------------------------------------------------
void FileStatusField::SetString(const char* val)
{
fString = val;
fClippedString = "";
fWidth = 0;
}
//--------------------------------------------------------------------
const char* FileStatusField::String() const
{
return fString.String();
}
//--------------------------------------------------------------------
void FileStatusField::SetWidth(float width)
{
fWidth = width;
}
//--------------------------------------------------------------------
float FileStatusField::Width()
{
return fWidth;
}
//--------------------------------------------------------------------
void FileStatusField::SetClippedString(const char* val)
{
fClippedString = val;
}
//--------------------------------------------------------------------
const char* FileStatusField::ClippedString()
{
return fClippedString.String();
}
//=====================================================================
FileStatusColumn::FileStatusColumn(const char* title, float width, float minWidth,
float maxWidth, uint32 truncate, alignment align)
:BTitledColumn(title, width, minWidth, maxWidth, align),
fTruncate(truncate)
{
}
//--------------------------------------------------------------------
void FileStatusColumn::DrawField(BField* _field, BRect rect, BView* parent)
{
FileStatusField* field = static_cast<FileStatusField*>(_field);
float width = rect.Width() - (2 * kTEXT_MARGIN);
float basePoint = 0;
if((field->GetFileStatus() == STOPPED && field->GetPercentage() > 0)||
field->GetFileStatus() == DOWNLOADING)
{
basePoint = 100 + kSPACE_TEXT;
}
if (width - basePoint != field->Width())
{
BString out_string(field->String());
parent->TruncateString(&out_string, fTruncate, width + 2 - basePoint);
field->SetClippedString(out_string.String());
field->SetWidth(width - basePoint);
}
if(basePoint>0){
DrawBar(parent,rect,field->GetPercentage());
}
rect.left +=basePoint;
DrawString(field->ClippedString(), parent, rect);
}
void
FileStatusColumn::DrawBar(BView* parent,BRect rect,int number)
{
parent->PushState();
//parent->SetDrawingMode( B_OP_ALPHA );
//parent->SetBlendingMode( B_PIXEL_ALPHA, B_ALPHA_OVERLAY);
BRect graphRect(rect);
graphRect.left += 2;
graphRect.right = graphRect.left + 99 + 1;
float offsetY = (graphRect.Height() - 12) / 2;
graphRect.top += offsetY;
graphRect.bottom -= offsetY;
number = number > 0 ? number : 1;
be_control_look->DrawStatusBar(parent, graphRect, graphRect,
ui_color(B_LIST_BACKGROUND_COLOR), ui_color(B_STATUS_BAR_COLOR),
graphRect.left + number);
parent->PopState();
}
//--------------------------------------------------------------------
int FileStatusColumn::CompareFields(BField* field1, BField* field2)
{
return(ICompare(((FileStatusField*)field1)->String(),
(((FileStatusField*)field2)->String())));
}
//--------------------------------------------------------------------
bool FileStatusColumn::AcceptsField(const BField *field) const
{
return static_cast<bool>(dynamic_cast<const FileStatusField*>(field));
}
<|endoftext|> |
<commit_before>#include "Chain.h"
#include <memory>
#include <array>
#include <algorithm>
#include "xoroshiro128plus.hpp"
#include <QDebug>
using namespace Xoroshiro;
Chain::Chain(QSize size)
: d_ptr(new ChainPrivate(size), &QObject::deleteLater)
{
}
Chain::Chain(const Chain &other)
: d_ptr(other.d_ptr)
{
}
Chain::operator QString() const {
return QString("Chain(%1x%2, %3)").arg(d_ptr->m_size.width()).arg(d_ptr->m_size.height()).arg(thread()->objectName());
}
QSize Chain::size() {
return d_ptr->m_size;
}
GLuint Chain::noiseTexture() {
if (!d_ptr->m_noiseTexture.isCreated()) {
d_ptr->m_noiseTexture.setSize(d_ptr->m_size.width(), d_ptr->m_size.height());
d_ptr->m_noiseTexture.setFormat(QOpenGLTexture::RGBA32F);
d_ptr->m_noiseTexture.allocateStorage(QOpenGLTexture::RGBA, QOpenGLTexture::Float32);
d_ptr->m_noiseTexture.setMinMagFilters(QOpenGLTexture::Linear, QOpenGLTexture::Linear);
d_ptr->m_noiseTexture.setWrapMode(QOpenGLTexture::Repeat);
auto compCount = d_ptr->m_size.width() * d_ptr->m_size.height() * 4;
auto data = std::make_unique<float[]>(compCount);
auto xsr = xoroshiro128plus_engine(reinterpret_cast<uint64_t>(this));
auto xsrd = [&xsr, div = (1./(UINT64_C(1)<<53))](){
return (xsr() >> 11) * div;
};
std::generate(&data[0],&data[compCount],xsrd);
d_ptr->m_noiseTexture.setData(QOpenGLTexture::RGBA, QOpenGLTexture::Float32, &data[0]);
glFlush();
if (QThread::currentThread() != thread()) {
moveToThread(QThread::currentThread());
}
}
return d_ptr->m_noiseTexture.textureId();
}
GLuint Chain::blankTexture() {
if (!d_ptr->m_blankTexture.isCreated()) {
d_ptr->m_blankTexture.setSize(1, 1);
d_ptr->m_blankTexture.setFormat(QOpenGLTexture::RGBA8_UNorm);
d_ptr->m_blankTexture.allocateStorage(QOpenGLTexture::RGBA, QOpenGLTexture::UInt8);
d_ptr->m_blankTexture.setMinMagFilters(QOpenGLTexture::Nearest, QOpenGLTexture::Nearest);
d_ptr->m_blankTexture.setWrapMode(QOpenGLTexture::Repeat);
auto data = std::array<uint8_t,4>();
d_ptr->m_blankTexture.setData(QOpenGLTexture::RGBA, QOpenGLTexture::UInt8, &data[0]);
if (QThread::currentThread() != thread()) {
moveToThread(QThread::currentThread());
}
}
return d_ptr->m_blankTexture.textureId();
}
QOpenGLVertexArrayObject *Chain::vao() {
if (!d_ptr->m_vao.isCreated()) {
d_ptr->m_vao.create();
if (QThread::currentThread() != thread()) {
moveToThread(QThread::currentThread());
}
}
return &d_ptr->m_vao;
}
bool Chain::operator==(const Chain &other) const {
return d_ptr == other.d_ptr;
}
bool Chain::operator>(const Chain &other) const {
return d_ptr.data() > other.d_ptr.data();
}
bool Chain::operator<(const Chain &other) const {
return d_ptr.data() > other.d_ptr.data();
}
Chain &Chain::operator=(const Chain &other) {
d_ptr = other.d_ptr;
return *this;
}
ChainPrivate::ChainPrivate(QSize size)
: m_noiseTexture(QOpenGLTexture::Target2D)
, m_blankTexture(QOpenGLTexture::Target2D)
, m_vao(new QOpenGLVertexArrayObject())
, m_size(size)
{
}
ChainPrivate::~ChainPrivate() {
}
<commit_msg>clarify deletion semantics<commit_after>#include "Chain.h"
#include <memory>
#include <array>
#include <algorithm>
#include "xoroshiro128plus.hpp"
#include <QDebug>
using namespace Xoroshiro;
Chain::Chain(QSize size)
: d_ptr(new ChainPrivate(size), &QObject::deleteLater)
{
}
Chain::Chain(const Chain &other)
: d_ptr(other.d_ptr)
{
}
Chain::operator QString() const {
return QString("Chain(%1x%2, %3)").arg(d_ptr->m_size.width()).arg(d_ptr->m_size.height()).arg(thread()->objectName());
}
QSize Chain::size() {
return d_ptr->m_size;
}
GLuint Chain::noiseTexture() {
if (!d_ptr->m_noiseTexture.isCreated()) {
d_ptr->m_noiseTexture.setSize(d_ptr->m_size.width(), d_ptr->m_size.height());
d_ptr->m_noiseTexture.setFormat(QOpenGLTexture::RGBA32F);
d_ptr->m_noiseTexture.allocateStorage(QOpenGLTexture::RGBA, QOpenGLTexture::Float32);
d_ptr->m_noiseTexture.setMinMagFilters(QOpenGLTexture::Linear, QOpenGLTexture::Linear);
d_ptr->m_noiseTexture.setWrapMode(QOpenGLTexture::Repeat);
auto compCount = d_ptr->m_size.width() * d_ptr->m_size.height() * 4;
auto data = std::make_unique<float[]>(compCount);
auto xsr = xoroshiro128plus_engine(reinterpret_cast<uint64_t>(this));
auto xsrd = [&xsr, div = (1./(UINT64_C(1)<<53))](){
return (xsr() >> 11) * div;
};
std::generate(&data[0],&data[compCount],xsrd);
d_ptr->m_noiseTexture.setData(QOpenGLTexture::RGBA, QOpenGLTexture::Float32, &data[0]);
glFlush();
if (QThread::currentThread() != d_ptr->thread()) {
d_ptr->moveToThread(QThread::currentThread());
}
}
return d_ptr->m_noiseTexture.textureId();
}
GLuint Chain::blankTexture() {
if (!d_ptr->m_blankTexture.isCreated()) {
d_ptr->m_blankTexture.setSize(1, 1);
d_ptr->m_blankTexture.setFormat(QOpenGLTexture::RGBA8_UNorm);
d_ptr->m_blankTexture.allocateStorage(QOpenGLTexture::RGBA, QOpenGLTexture::UInt8);
d_ptr->m_blankTexture.setMinMagFilters(QOpenGLTexture::Nearest, QOpenGLTexture::Nearest);
d_ptr->m_blankTexture.setWrapMode(QOpenGLTexture::Repeat);
auto data = std::array<uint8_t,4>();
d_ptr->m_blankTexture.setData(QOpenGLTexture::RGBA, QOpenGLTexture::UInt8, &data[0]);
if (QThread::currentThread() != d_ptr->thread()) {
d_ptr->moveToThread(QThread::currentThread());
}
}
return d_ptr->m_blankTexture.textureId();
}
QOpenGLVertexArrayObject *Chain::vao() {
if (!d_ptr->m_vao.isCreated()) {
d_ptr->m_vao.create();
if (QThread::currentThread() != d_ptr->thread()) {
d_ptr->moveToThread(QThread::currentThread());
}
}
return &d_ptr->m_vao;
}
bool Chain::operator==(const Chain &other) const {
return d_ptr == other.d_ptr;
}
bool Chain::operator>(const Chain &other) const {
return d_ptr.data() > other.d_ptr.data();
}
bool Chain::operator<(const Chain &other) const {
return d_ptr.data() > other.d_ptr.data();
}
Chain &Chain::operator=(const Chain &other) {
d_ptr = other.d_ptr;
return *this;
}
ChainPrivate::ChainPrivate(QSize size)
: m_noiseTexture(QOpenGLTexture::Target2D)
, m_blankTexture(QOpenGLTexture::Target2D)
, m_vao(new QOpenGLVertexArrayObject())
, m_size(size)
{
}
ChainPrivate::~ChainPrivate() {
}
<|endoftext|> |
<commit_before>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
#define S_FUNCTION_NAME HopsanSimulink
#define S_FUNCTION_LEVEL 2
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <fstream>
#include "simstruc.h"
#include "HopsanCore/include/HopsanCore.h"
using namespace hopsan;
//! @todo need to be able to error report if file not fond, or maybe not, if no external libs used you dont want error message
void readExternalLibsFromTxtFile(const std::string filePath, std::vector<std::string> &rExtLibFileNames)
{
rExtLibFileNames.clear();
std::string line;
std::ifstream file;
file.open(filePath.c_str());
if ( file.is_open() )
{
while ( file.good() )
{
getline(file, line);
if ((*line.begin() != '#') && !line.empty())
{
rExtLibFileNames.push_back(line);
}
}
file.close();
}
else
{
std::cout << "error, could not open file: " << filePath << std::endl;
}
}
HopsanEssentials gHopsanCore;
ComponentSystem* pComponentSystem;
bool isOkToSimulate = false;
<<<15>>>
static void mdlInitializeSizes(SimStruct *S)
{
ssSetNumSFcnParams(S, 0);
if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S))
{
return;
}
//Define S-function input signals
if (!ssSetNumInputPorts(S,<<<0>>>)) return; //Number of input signals
<<<1>>>
//Define S-function output signals
if (!ssSetNumOutputPorts(S,<<<2>>>)) return; //Number of output signals
<<<3>>>
ssSetOutputPortWidth(S, <<<14>>>, DYNAMICALLY_SIZED); //Debug output signal
ssSetNumSampleTimes(S, 1);
ssSetOptions(S, SS_OPTION_EXCEPTION_FREE_CODE);
std::vector<std::string> extLibs;
readExternalLibsFromTxtFile("externalLibs.txt",extLibs);
for (size_t i=0; i<extLibs.size(); ++i)
{
gHopsanCore.loadExternalComponentLib(extLibs[i].c_str());
}
const char* hmfFilePath = "<<<4>>>";
double startT, stopT;
pComponentSystem = gHopsanCore.loadHMFModel(hmfFilePath, startT, stopT);
if (pComponentSystem==0)
{
ssSetErrorStatus(S,"Error could not open model: <<<4>>>");
return;
}
startT = ssGetTStart(S);
stopT = ssGetTFinal(S);
pComponentSystem->setDesiredTimestep(0.001);
<<<5>>>}
static void mdlInitializeSampleTimes(SimStruct *S)
{
ssSetSampleTime(S, 0, 0.001);
ssSetOffsetTime(S, 0, 0.0);
//Update tunable parameters
const mxArray* in;
const char* c_str;
std::string str;
<<<6>>>
isOkToSimulate = pComponentSystem->checkModelBeforeSimulation();
if (isOkToSimulate)
{
pComponentSystem->setNumLogSamples(0);
pComponentSystem->disableLog();
pComponentSystem->initialize(0,1);
}
else
{
ssSetErrorStatus(S,"Error isSimulationOk() returned False! Most likely some components could not be loaded or some connections could not be established.");
return;
}
<<<16>>>}
static void mdlOutputs(SimStruct *S, int_T tid)
{
//S-function input signals
InputRealPtrsType uPtrs1 = ssGetInputPortRealSignalPtrs(S,0);
//S-function output signals
<<<7>>>
int_T width1 = ssGetOutputPortWidth(S,0);
//Input parameters
<<<8>>>
//Equations
<<<9>>>
output<<<10>>> = 0; //Error code 0: Nothing is wrong
<<<11>>>
double timestep = pComponentSystem->getDesiredTimeStep();
double time = ssGetT(S);
pComponentSystem->simulate(time+timestep);
<<<12>>>
//Output parameters
<<<13>>>}
static void mdlTerminate(SimStruct *S){}
/* Simulink/Simulink Coder Interfaces */
#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */
#include "simulink.c" /* MEX-file interface mechanism */
#else
#include "cg_sfun.h" /* Code generation registration function */
#endif
<commit_msg>Added finalize call in Simulink export. Needs to be validated in Windows. Related to #853.<commit_after>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
#define S_FUNCTION_NAME HopsanSimulink
#define S_FUNCTION_LEVEL 2
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <fstream>
#include "simstruc.h"
#include "HopsanCore/include/HopsanCore.h"
using namespace hopsan;
//! @todo need to be able to error report if file not fond, or maybe not, if no external libs used you dont want error message
void readExternalLibsFromTxtFile(const std::string filePath, std::vector<std::string> &rExtLibFileNames)
{
rExtLibFileNames.clear();
std::string line;
std::ifstream file;
file.open(filePath.c_str());
if ( file.is_open() )
{
while ( file.good() )
{
getline(file, line);
if ((*line.begin() != '#') && !line.empty())
{
rExtLibFileNames.push_back(line);
}
}
file.close();
}
else
{
std::cout << "error, could not open file: " << filePath << std::endl;
}
}
HopsanEssentials gHopsanCore;
ComponentSystem* pComponentSystem;
bool isOkToSimulate = false;
<<<15>>>
static void mdlInitializeSizes(SimStruct *S)
{
ssSetNumSFcnParams(S, 0);
if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S))
{
return;
}
//Define S-function input signals
if (!ssSetNumInputPorts(S,<<<0>>>)) return; //Number of input signals
<<<1>>>
//Define S-function output signals
if (!ssSetNumOutputPorts(S,<<<2>>>)) return; //Number of output signals
<<<3>>>
ssSetOutputPortWidth(S, <<<14>>>, DYNAMICALLY_SIZED); //Debug output signal
ssSetNumSampleTimes(S, 1);
ssSetOptions(S, SS_OPTION_EXCEPTION_FREE_CODE);
std::vector<std::string> extLibs;
readExternalLibsFromTxtFile("externalLibs.txt",extLibs);
for (size_t i=0; i<extLibs.size(); ++i)
{
gHopsanCore.loadExternalComponentLib(extLibs[i].c_str());
}
const char* hmfFilePath = "<<<4>>>";
double startT, stopT;
pComponentSystem = gHopsanCore.loadHMFModel(hmfFilePath, startT, stopT);
if (pComponentSystem==0)
{
ssSetErrorStatus(S,"Error could not open model: <<<4>>>");
return;
}
startT = ssGetTStart(S);
stopT = ssGetTFinal(S);
pComponentSystem->setDesiredTimestep(0.001);
<<<5>>>}
static void mdlInitializeSampleTimes(SimStruct *S)
{
ssSetSampleTime(S, 0, 0.001);
ssSetOffsetTime(S, 0, 0.0);
//Update tunable parameters
const mxArray* in;
const char* c_str;
std::string str;
<<<6>>>
isOkToSimulate = pComponentSystem->checkModelBeforeSimulation();
if (isOkToSimulate)
{
pComponentSystem->setNumLogSamples(0);
pComponentSystem->disableLog();
pComponentSystem->initialize(0,1);
}
else
{
ssSetErrorStatus(S,"Error isSimulationOk() returned False! Most likely some components could not be loaded or some connections could not be established.");
return;
}
<<<16>>>}
static void mdlOutputs(SimStruct *S, int_T tid)
{
//S-function input signals
InputRealPtrsType uPtrs1 = ssGetInputPortRealSignalPtrs(S,0);
//S-function output signals
<<<7>>>
int_T width1 = ssGetOutputPortWidth(S,0);
//Input parameters
<<<8>>>
//Equations
<<<9>>>
output<<<10>>> = 0; //Error code 0: Nothing is wrong
<<<11>>>
double timestep = pComponentSystem->getDesiredTimeStep();
double time = ssGetT(S);
pComponentSystem->simulate(time+timestep);
<<<12>>>
//Output parameters
<<<13>>>}
static void mdlTerminate(SimStruct *S)
{
pComponentSystem->finalize();
}
/* Simulink/Simulink Coder Interfaces */
#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */
#include "simulink.c" /* MEX-file interface mechanism */
#else
#include "cg_sfun.h" /* Code generation registration function */
#endif
<|endoftext|> |
<commit_before>#include "Wavenet/Coach.h"
#include "Wavenet/Generators.h" /* To determine whether generator has natural epochs. */
namespace wavenet {
void Coach::setBasedir (const std::string& basedir) {
m_basedir = basedir;
if (strcmp(&m_basedir.back(), "/") == 0) { m_basedir.append("/"); }
return;
}
void Coach::setNumEvents (const int& numEvents) {
if (numEvents < 0 and numEvents != -1) {
WARNING("Input number of events (%d) not supported.", numEvents);
return;
}
m_numEvents = numEvents;
return;
}
void Coach::setNumCoeffs (const unsigned& numCoeffs) {
if (!isRadix2(numCoeffs)) {
WARNING("Input number of coefficients (%d) is not radix 2.", numCoeffs);
return;
}
m_numCoeffs = numCoeffs;
return;
}
void Coach::setTargetPrecision (const double& targetPrecision) {
if (targetPrecision != -1 && targetPrecision <= 0) {
WARNING("Requested target precision (%f) is no good. Exiting.", targetPrecision);
return;
}
if (!(useAdaptiveLearningRate() || useAdaptiveBatchSize())) {
WARNING("Target precision is to be used in conjuction with 'adaptive learning rate' or 'adaptive batch size'.");
WARNING("Remember to set it using 'Coach::setUseAdaptiveLearningRate()' or 'Coach::setUseAdaptiveBatchSize()'.");
WARNING(" Going to continue, but the set value of target precision won't have any effect on its own.");
}
m_targetPrecision = targetPrecision;
return;
}
void Coach::checkMakeOutdir (const std::string& subdir) const {
// Perform checks.
if (m_basedir == "" || outdir() == "") {
WARNING("Directory not set.");
return;
}
if (strcmp(outdir().substr(0,1).c_str(), "/") == 0) {
WARNING("Directory '%s' not accepted. Only accepting realtive paths.", outdir().c_str());
return;
}
const std::string dir = outdir() + subdir;
if (dirExists(dir)) {
DEBUG("Directory '%s' already exists. Exiting.", dir.c_str());
return;
}
// Create the directory.
INFO("Creating directory '%s'.", dir.c_str());
system(("mkdir -p " + dir).c_str());
return;
}
bool Coach::run () {
// Perform checks.
if (!m_wavenet) {
ERROR("WaveletML object not set.Exiting.");
return false;
}
if (!m_generator) {
ERROR("Input generator not set. Exiting.");
return false;
}
if (!m_generator->initialised()) {
ERROR("Generator was not properly initialised. Did you remember to specify a valid shape? Exiting.");
return false;
}
if (!m_name.size()) {
ERROR("Coach name not set. Exiting.");
return false;
}
if (m_numEvents < 0) {
if ((dynamic_cast<NeedleGenerator*> (m_generator) != nullptr ||
dynamic_cast<UniformGenerator*> (m_generator) != nullptr ||
dynamic_cast<GaussianGenerator*>(m_generator) != nullptr) &&
!((useAdaptiveLearningRate() || useAdaptiveBatchSize()) && targetPrecision() > 0.)) {
WARNING("The number of events is set to %d while using", m_numEvents);
WARNING(".. a generator with no natural epochs and with");
WARNING(".. no target precision set. Etiher choose a ");
WARNING(".. different generator or use");
WARNING(".. 'Coach::setUseAdaptiveLearningRate()' or")
WARNING(".. 'Coach::setUseAdaptiveLearningRate()', and");
WARNING("'Coach::setTargetPrecision(someValue)'.");
WARNING("Exiting.");
return false;
}
}
INFO("Start training, using coach '%s'.", m_name.c_str());
// Save base snapshot of initial condition, so as to be able to restore same
// configuration for each intitialisation (in particular, to roll back
//changes made by adaptive learning methods.)
Snapshot baseSnap (outdir() + "snapshots/.tmp.snap");
m_wavenet->save(baseSnap);
// Define number of trailing steps, for use with adaptive learning rate.
const unsigned useLastN = 10;
// Definition bare, specified regularsation constant, for use with simulated
// annealing.
const double lambdaBare = m_wavenet->lambda();
// Define snapshot object, for saving the final configuration for each
// initialisation.
Snapshot snap (outdir() + "snapshots/" + m_name + ".%06u.snap", 0);
// Loop initialisations.
for (unsigned init = 0; init < m_numInits; init++) {
// Print progress.
if (m_printLevel > 0) {
INFO("Initialisation %d/%d", init + 1, m_numInits);
}
// Load base snapshot.
m_wavenet->load(baseSnap);
m_wavenet->clear();
// Generate initial coefficient configuration as random point on unit
// N-sphere. In this way we immediately fullfill one out of the (at
// most) four (non-trivial) conditions on the filter coefficients.
m_wavenet->setFilter( PointOnNSphere(m_numCoeffs) );
// Definitions for adaptive learning.
bool done = false; // Whether the training is done, i.e. whether to
// break training early
unsigned tail = 0; // The number of updates since beginning of training
// or last update of the learning rate, whichever is
// latest.
unsigned currentCostLogSize = 0; // Number of entries in cost log, now
unsigned previousCostLogSize = 0; // and at previous step in the loop.
// Used to determine whether a batch
// update occurred.
// Get the number of digits to use when printing the number of events.
const unsigned eventDigits = (m_numEvents > 0 ? unsigned(log10(m_numEvents)) + 1 : 1);
// Loop epochs.
for (unsigned epoch = 0; epoch < m_numEpochs; epoch++) {
// Reset (re-open) generator.
m_generator->reset();
// Print progress.
if (m_printLevel > 1) {
INFO(" Epoch %d/%d", epoch + 1, m_numEpochs);
}
// Loop events.
int event = 0;
int eventPrint = m_wavenet->batchSize();
do {
// Simulated annealing.
if (useSimulatedAnnealing()) {
const double f = (event + epoch * numEvents()) / float(numEvents() * numEpochs());
const double effectiveLambda = lambdaBare * f / sq(2 - f);
m_wavenet->setLambda(effectiveLambda);
}
// Main training call.
bool status = m_wavenet->train( m_generator->next() );
// In case something goes wrong.
if (!status) {
done = true;
break;
}
// Adaptive learning rate.
if (useAdaptiveLearningRate() || useAdaptiveBatchSize()) {
// Determine whether a batch upate took place, by checking
// whether the size of the cost log changed.
previousCostLogSize = currentCostLogSize;
currentCostLogSize = m_wavenet->costLog().size();
bool changed = (currentCostLogSize != previousCostLogSize);
// If it changed and the tail (number of updates since last
// learning rate update) is sufficiently large, initiate
// adaptation.
if (changed && ++tail > useLastN) {
const unsigned filterLogSize = m_wavenet->filterLog().size();
// Compute the (vector) size of the last N steps in the
// SGD, as well as the mean (scalar) size of these.
std::vector< arma::Col<double> > lastNsteps(useLastN);
double meanStepSize = 0;
for (unsigned i = 0; i < useLastN; i++) {
lastNsteps.at(i) = m_wavenet->filterLog().at(filterLogSize - useLastN + i) - m_wavenet->filterLog().at(filterLogSize - useLastN + i - 1);
meanStepSize += arma::norm(lastNsteps.at(i));
}
meanStepSize /= float(useLastN);
// Compute the total (vector) size of the last N steps
// in the SGD combined, as well as the (scalar) size.
arma::Col<double> totalStep = m_wavenet->filterLog().at(filterLogSize - 1) - m_wavenet->filterLog().at(filterLogSize - 1 - useLastN);
double totalStepSize = arma::norm(totalStep);
// Check whether we have reached target precision or
// whether to perform adaptive learning rate update.
if (targetPrecision() != -1 && meanStepSize < targetPrecision() && !useSimulatedAnnealing()) {
INFO("[Adaptive learning] The mean step size over the last %d updates (%f)", useLastN, meanStepSize);
INFO("[Adaptive learning] is smaller than the target precision (%f). Done.", targetPrecision());
done = true;
} else if (totalStepSize < meanStepSize) {
INFO("[Adaptive learning] Total step size (%f) is smaller than mean step size (%f).", totalStepSize, meanStepSize);
// Update batch size.
if (useAdaptiveBatchSize()) {
INFO("[Adaptive learning] Increasing batch size from %d to %d.", m_wavenet->batchSize(), 2 * m_wavenet->batchSize());
m_wavenet->setBatchSize( 2 * m_wavenet->batchSize() );
}
// Update learning rate.
if (useAdaptiveLearningRate()) {
INFO("[Adaptive learning] Reducing learning rate (alpha) from %f to %f.", m_wavenet->alpha(), (1./2.) * m_wavenet->alpha() ); //* (totalStepSize/meanStepSize));
m_wavenet->setAlpha( (1./2.) * m_wavenet->alpha() ); // * (totalStepSize/meanStepSize));
}
tail = 0;
}
}
}
// Print progress.
if (m_printLevel > 2 && ((event + 1) % eventPrint == 0 || event + 1 == m_numEvents)) {
if (m_numEvents == -1) { INFO(" Event %*d/- (cost: %7.3f)", eventDigits, event + 1, m_wavenet->lastCost()); }
else { INFO(" Event %*d/%*d (cost: %7.3f)", eventDigits, event + 1, eventDigits, m_numEvents, m_wavenet->lastCost()); }
if ((event + 1) == 10 * eventPrint) { eventPrint *= 10; }
}
// Increment event number. (Only level not in a for-loop, since
// the number of events may be unspecified, i.e. be -1.)
++event;
// If the generator is not in a good condition, break.
if (!m_generator->good()) { break; }
} while (!done && (event < m_numEvents || m_numEvents < 0 ));
if (done) { break; }
}
// Clean up, by removing the last entry in the cost log, which isn't
// properly scaled to batch size since the batch queue hasn't been flushed,
// and therefore might bias result.
m_wavenet->costLog().pop_back();
// Saving snapshot to file.
m_wavenet->save(snap++);
}
// Writing setup to run-specific README file.
INFO("Writing run configuration to '%s'.", (outdir() + "README").c_str());
std::ofstream outFileStream (outdir() + "README");
outFileStream << "m_numEvents: " << m_numEvents << "\n";
outFileStream << "m_numEpochs: " << m_numEpochs << "\n";
outFileStream << "m_numInits: " << m_numInits << "\n";
outFileStream << "m_numCoeffs: " << m_numCoeffs << "\n";
outFileStream.close();
// Clean up.
m_wavenet->clear();
return true;
}
} // namespace
<commit_msg>Don't clear wavenet object after training.<commit_after>#include "Wavenet/Coach.h"
#include "Wavenet/Generators.h" /* To determine whether generator has natural epochs. */
namespace wavenet {
void Coach::setBasedir (const std::string& basedir) {
m_basedir = basedir;
if (strcmp(&m_basedir.back(), "/") == 0) { m_basedir.append("/"); }
return;
}
void Coach::setNumEvents (const int& numEvents) {
if (numEvents < 0 and numEvents != -1) {
WARNING("Input number of events (%d) not supported.", numEvents);
return;
}
m_numEvents = numEvents;
return;
}
void Coach::setNumCoeffs (const unsigned& numCoeffs) {
if (!isRadix2(numCoeffs)) {
WARNING("Input number of coefficients (%d) is not radix 2.", numCoeffs);
return;
}
m_numCoeffs = numCoeffs;
return;
}
void Coach::setTargetPrecision (const double& targetPrecision) {
if (targetPrecision != -1 && targetPrecision <= 0) {
WARNING("Requested target precision (%f) is no good. Exiting.", targetPrecision);
return;
}
if (!(useAdaptiveLearningRate() || useAdaptiveBatchSize())) {
WARNING("Target precision is to be used in conjuction with 'adaptive learning rate' or 'adaptive batch size'.");
WARNING("Remember to set it using 'Coach::setUseAdaptiveLearningRate()' or 'Coach::setUseAdaptiveBatchSize()'.");
WARNING(" Going to continue, but the set value of target precision won't have any effect on its own.");
}
m_targetPrecision = targetPrecision;
return;
}
void Coach::checkMakeOutdir (const std::string& subdir) const {
// Perform checks.
if (m_basedir == "" || outdir() == "") {
WARNING("Directory not set.");
return;
}
if (strcmp(outdir().substr(0,1).c_str(), "/") == 0) {
WARNING("Directory '%s' not accepted. Only accepting realtive paths.", outdir().c_str());
return;
}
const std::string dir = outdir() + subdir;
if (dirExists(dir)) {
DEBUG("Directory '%s' already exists. Exiting.", dir.c_str());
return;
}
// Create the directory.
INFO("Creating directory '%s'.", dir.c_str());
system(("mkdir -p " + dir).c_str());
return;
}
bool Coach::run () {
// Perform checks.
if (!m_wavenet) {
ERROR("WaveletML object not set.Exiting.");
return false;
}
if (!m_generator) {
ERROR("Input generator not set. Exiting.");
return false;
}
if (!m_generator->initialised()) {
ERROR("Generator was not properly initialised. Did you remember to specify a valid shape? Exiting.");
return false;
}
if (!m_name.size()) {
ERROR("Coach name not set. Exiting.");
return false;
}
if (m_numEvents < 0) {
if ((dynamic_cast<NeedleGenerator*> (m_generator) != nullptr ||
dynamic_cast<UniformGenerator*> (m_generator) != nullptr ||
dynamic_cast<GaussianGenerator*>(m_generator) != nullptr) &&
!((useAdaptiveLearningRate() || useAdaptiveBatchSize()) && targetPrecision() > 0.)) {
WARNING("The number of events is set to %d while using", m_numEvents);
WARNING(".. a generator with no natural epochs and with");
WARNING(".. no target precision set. Etiher choose a ");
WARNING(".. different generator or use");
WARNING(".. 'Coach::setUseAdaptiveLearningRate()' or")
WARNING(".. 'Coach::setUseAdaptiveLearningRate()', and");
WARNING("'Coach::setTargetPrecision(someValue)'.");
WARNING("Exiting.");
return false;
}
}
INFO("Start training, using coach '%s'.", m_name.c_str());
// Save base snapshot of initial condition, so as to be able to restore same
// configuration for each intitialisation (in particular, to roll back
//changes made by adaptive learning methods.)
Snapshot baseSnap (outdir() + "snapshots/.tmp.snap");
m_wavenet->save(baseSnap);
// Define number of trailing steps, for use with adaptive learning rate.
const unsigned useLastN = 10;
// Definition bare, specified regularsation constant, for use with simulated
// annealing.
const double lambdaBare = m_wavenet->lambda();
// Define snapshot object, for saving the final configuration for each
// initialisation.
Snapshot snap (outdir() + "snapshots/" + m_name + ".%06u.snap", 0);
// Loop initialisations.
for (unsigned init = 0; init < m_numInits; init++) {
// Print progress.
if (m_printLevel > 0) {
INFO("Initialisation %d/%d", init + 1, m_numInits);
}
// Load base snapshot.
m_wavenet->load(baseSnap);
m_wavenet->clear();
// Generate initial coefficient configuration as random point on unit
// N-sphere. In this way we immediately fullfill one out of the (at
// most) four (non-trivial) conditions on the filter coefficients.
m_wavenet->setFilter( PointOnNSphere(m_numCoeffs) );
// Definitions for adaptive learning.
bool done = false; // Whether the training is done, i.e. whether to
// break training early
unsigned tail = 0; // The number of updates since beginning of training
// or last update of the learning rate, whichever is
// latest.
unsigned currentCostLogSize = 0; // Number of entries in cost log, now
unsigned previousCostLogSize = 0; // and at previous step in the loop.
// Used to determine whether a batch
// update occurred.
// Get the number of digits to use when printing the number of events.
const unsigned eventDigits = (m_numEvents > 0 ? unsigned(log10(m_numEvents)) + 1 : 1);
// Loop epochs.
for (unsigned epoch = 0; epoch < m_numEpochs; epoch++) {
// Reset (re-open) generator.
m_generator->reset();
// Print progress.
if (m_printLevel > 1) {
INFO(" Epoch %d/%d", epoch + 1, m_numEpochs);
}
// Loop events.
int event = 0;
int eventPrint = m_wavenet->batchSize();
do {
// Simulated annealing.
if (useSimulatedAnnealing()) {
const double f = (event + epoch * numEvents()) / float(numEvents() * numEpochs());
const double effectiveLambda = lambdaBare * f / sq(2 - f);
m_wavenet->setLambda(effectiveLambda);
}
// Main training call.
bool status = m_wavenet->train( m_generator->next() );
// In case something goes wrong.
if (!status) {
done = true;
break;
}
// Adaptive learning rate.
if (useAdaptiveLearningRate() || useAdaptiveBatchSize()) {
// Determine whether a batch upate took place, by checking
// whether the size of the cost log changed.
previousCostLogSize = currentCostLogSize;
currentCostLogSize = m_wavenet->costLog().size();
bool changed = (currentCostLogSize != previousCostLogSize);
// If it changed and the tail (number of updates since last
// learning rate update) is sufficiently large, initiate
// adaptation.
if (changed && ++tail > useLastN) {
const unsigned filterLogSize = m_wavenet->filterLog().size();
// Compute the (vector) size of the last N steps in the
// SGD, as well as the mean (scalar) size of these.
std::vector< arma::Col<double> > lastNsteps(useLastN);
double meanStepSize = 0;
for (unsigned i = 0; i < useLastN; i++) {
lastNsteps.at(i) = m_wavenet->filterLog().at(filterLogSize - useLastN + i) - m_wavenet->filterLog().at(filterLogSize - useLastN + i - 1);
meanStepSize += arma::norm(lastNsteps.at(i));
}
meanStepSize /= float(useLastN);
// Compute the total (vector) size of the last N steps
// in the SGD combined, as well as the (scalar) size.
arma::Col<double> totalStep = m_wavenet->filterLog().at(filterLogSize - 1) - m_wavenet->filterLog().at(filterLogSize - 1 - useLastN);
double totalStepSize = arma::norm(totalStep);
// Check whether we have reached target precision or
// whether to perform adaptive learning rate update.
if (targetPrecision() != -1 && meanStepSize < targetPrecision() && !useSimulatedAnnealing()) {
INFO("[Adaptive learning] The mean step size over the last %d updates (%f)", useLastN, meanStepSize);
INFO("[Adaptive learning] is smaller than the target precision (%f). Done.", targetPrecision());
done = true;
} else if (totalStepSize < meanStepSize) {
INFO("[Adaptive learning] Total step size (%f) is smaller than mean step size (%f).", totalStepSize, meanStepSize);
// Update batch size.
if (useAdaptiveBatchSize()) {
INFO("[Adaptive learning] Increasing batch size from %d to %d.", m_wavenet->batchSize(), 2 * m_wavenet->batchSize());
m_wavenet->setBatchSize( 2 * m_wavenet->batchSize() );
}
// Update learning rate.
if (useAdaptiveLearningRate()) {
INFO("[Adaptive learning] Reducing learning rate (alpha) from %f to %f.", m_wavenet->alpha(), (1./2.) * m_wavenet->alpha() ); //* (totalStepSize/meanStepSize));
m_wavenet->setAlpha( (1./2.) * m_wavenet->alpha() ); // * (totalStepSize/meanStepSize));
}
tail = 0;
}
}
}
// Print progress.
if (m_printLevel > 2 && ((event + 1) % eventPrint == 0 || event + 1 == m_numEvents)) {
if (m_numEvents == -1) { INFO(" Event %*d/- (cost: %7.3f)", eventDigits, event + 1, m_wavenet->lastCost()); }
else { INFO(" Event %*d/%*d (cost: %7.3f)", eventDigits, event + 1, eventDigits, m_numEvents, m_wavenet->lastCost()); }
if ((event + 1) == 10 * eventPrint) { eventPrint *= 10; }
}
// Increment event number. (Only level not in a for-loop, since
// the number of events may be unspecified, i.e. be -1.)
++event;
// If the generator is not in a good condition, break.
if (!m_generator->good()) { break; }
} while (!done && (event < m_numEvents || m_numEvents < 0 ));
if (done) { break; }
}
// Clean up, by removing the last entry in the cost log, which isn't
// properly scaled to batch size since the batch queue hasn't been flushed,
// and therefore might bias result.
m_wavenet->costLog().pop_back();
// Saving snapshot to file.
m_wavenet->save(snap++);
}
// Writing setup to run-specific README file.
INFO("Writing run configuration to '%s'.", (outdir() + "README").c_str());
std::ofstream outFileStream (outdir() + "README");
outFileStream << "m_numEvents: " << m_numEvents << "\n";
outFileStream << "m_numEpochs: " << m_numEpochs << "\n";
outFileStream << "m_numInits: " << m_numInits << "\n";
outFileStream << "m_numCoeffs: " << m_numCoeffs << "\n";
outFileStream.close();
// We're not clearing the wavenet object, since it might be useful to look
// at the filter- and cost log immediately after training (i.e. without
// interacting with Snapshots).
return true;
}
} // namespace
<|endoftext|> |
<commit_before>/**
* main.cpp
* This file is part of MultitouchPadOsc
*
*
* The MIT License
* Copyright (c) 2012 Paul Vollmer, http://www.wrong-entertainment.com
* All rights reserved.
*
* 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.
*
*
* @plattform MacOs 10.6+
* Win XXX
* Linux XXX
* @openFrameworks 0071
* @dependencies
* @modified 2012.07.15
* @version 0.1.2
*/
#include "ofMain.h"
#include "MultitouchPadOscApp.h"
#include "ofAppGlutWindow.h"
#include "Cocoa/Cocoa.h"
int main() {
ofAppGlutWindow window;
ofSetupOpenGL(&window, 600, 600, OF_WINDOW); // setup the GL context
if (NSApp){
NSMenu *menu;
NSMenuItem *menuItem;
[NSApp setMainMenu:[[NSMenu alloc] init]];
// Appname menu
menu = [[NSMenu alloc] initWithTitle:@""];
[menu addItemWithTitle:@"About MultitouchPadOsc" action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
[menu addItem:[NSMenuItem separatorItem]];
[menu addItemWithTitle:@"Hide MultitouchPadOsc" action:@selector(hide:) keyEquivalent:@"h"];
menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
[menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
[menu addItem:[NSMenuItem separatorItem]];
[menu addItemWithTitle:@"Quit MultitouchPadOsc" action:@selector(terminate:) keyEquivalent:@"q"];
// Put menu into the menubar
menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
[menuItem setSubmenu:menu];
[[NSApp mainMenu] addItem:menuItem];
// Tell the application object that this is now the application menu
//[NSApp setMainMenu:menu];
}
// this kicks off the running of my app can be
// OF_WINDOW or OF_FULLSCREEN pass in width and height too:
ofRunApp(new MultitouchPadOscApp());
}
<commit_msg>changed window size<commit_after>/**
* main.cpp
* This file is part of MultitouchPadOsc
*
*
* The MIT License
* Copyright (c) 2012 Paul Vollmer, http://www.wrong-entertainment.com
* All rights reserved.
*
* 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.
*
*
* @plattform MacOs 10.6+
* Win XXX
* Linux XXX
* @openFrameworks 0071
* @dependencies
* @modified 2012.07.15
* @version 0.1.2
*/
#include "ofMain.h"
#include "MultitouchPadOscApp.h"
#include "ofAppGlutWindow.h"
#include "Cocoa/Cocoa.h"
int main() {
ofAppGlutWindow window;
ofSetupOpenGL(&window, 500, 400, OF_WINDOW); // setup the GL context
if (NSApp){
NSMenu *menu;
NSMenuItem *menuItem;
[NSApp setMainMenu:[[NSMenu alloc] init]];
// Appname menu
menu = [[NSMenu alloc] initWithTitle:@""];
[menu addItemWithTitle:@"About MultitouchPadOsc" action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
[menu addItem:[NSMenuItem separatorItem]];
[menu addItemWithTitle:@"Hide MultitouchPadOsc" action:@selector(hide:) keyEquivalent:@"h"];
menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
[menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
[menu addItem:[NSMenuItem separatorItem]];
[menu addItemWithTitle:@"Quit MultitouchPadOsc" action:@selector(terminate:) keyEquivalent:@"q"];
// Put menu into the menubar
menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
[menuItem setSubmenu:menu];
[[NSApp mainMenu] addItem:menuItem];
// Tell the application object that this is now the application menu
//[NSApp setMainMenu:menu];
}
// this kicks off the running of my app can be
// OF_WINDOW or OF_FULLSCREEN pass in width and height too:
ofRunApp(new MultitouchPadOscApp());
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cmath>
#include <ctime>
#include <GL/glut.h>
#include <assert.h>
#include <cstdlib>
#include "main.hpp"
#include "Scene.hpp"
// don't define anything in headers! only declare it!!!1!one!
Vec3Df MyCameraPosition;
// double buffered
unsigned int textures[2];
unsigned int activeTexIndex = 0;
unsigned int isDrawingTexture = 0;
unsigned int isRealtimeRaytracing = 0;
Tree MyTree;
Scene MyScene;
// options
extern bool g_phong;
extern bool g_checkerboard;
extern bool g_debug;
bool needRebuild = false; // if the raytrace needs to be built
/**
* draw a full-screen texture
*/
void drawTexture(int texIndex){
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textures[texIndex]);
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex3f(0, 0, 0);
glTexCoord2f(1, 0);
glVertex3f(4, 0, 0);
glTexCoord2f(1, 1);
glVertex3f(4, 4, 0);
glTexCoord2f(0, 1);
glVertex3f(0, 4, 0);
glEnd();
}
void animate() {
MyCameraPosition = getCameraPosition();
glutPostRedisplay();
}
void display(void);
void reshape(int w, int h);
void keyboard(unsigned char key, int x, int y);
// entry point
int main(int argc, char** argv){
glutInit(&argc, argv);
// couches du framebuffer utilisees par l'application
glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
// position et taille de la fenetre
glutInitWindowPosition(200, 100);
glutInitWindowSize(WINDOW_RES_X, WINDOW_RES_Y);
glutCreateWindow(argv[0]);
// Initialisation du point de vue
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0, 0, -4);
glRotatef(0, -1, 1, 1);
tbInitTransform(); // initialisation du point de vue
tbHelp(); // affiche l'aide sur la traqueboule
MyCameraPosition = getCameraPosition();
//
// Active la lumière
// Pour la partie
// ECLAIRAGE
glEnable( GL_LIGHTING);
glEnable( GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
int LightPos[4] = {0, 0, 3, 1};
glLightiv(GL_LIGHT0, GL_POSITION, LightPos);
//glMaterialiv(GL_FRONT_AND_BACK,GL_SPECULAR,MatSpec);
//glMateriali(GL_FRONT_AND_BACK,GL_SHININESS,10);
glEnable(GL_NORMALIZE);
glClearColor(0.0, 0.0, 0.0, 0.0);
// Details sur le mode de tracé
glEnable( GL_DEPTH_TEST); // effectuer le test de profondeur
//glEnable(GL_CULL_FACE);
//glCullFace(GL_BACK);
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_LINE);
glShadeModel(GL_SMOOTH);
// init textures
char* buf = new char[1024 * 1024 * 3];
glGenTextures(2, textures);
// texture 1
glBindTexture(GL_TEXTURE_2D, textures[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1024, 1024, 0, GL_RGB,
GL_UNSIGNED_BYTE, buf);
// texture 2
glBindTexture(GL_TEXTURE_2D, textures[1]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1024, 1024, 0, GL_RGB,
GL_UNSIGNED_BYTE, buf);
delete[] buf;
// cablage des callback
glutReshapeFunc(reshape);
glutSetKeyRepeat(true);
glutKeyboardFunc(keyboard);
glutKeyboardUpFunc(keyup);
glutDisplayFunc(display);
glutMouseFunc(tbMouseFunc); // traqueboule utilise la souris
glutMotionFunc(tbMotionFunc); // traqueboule utilise la souris
glutIdleFunc(animate);
int ret = init(argc, argv);
if(ret == 255)
return 0;
if(ret > 0)
return ret;
// lancement de la boucle principale
glutMainLoop();
return 0; // instruction jamais exécutée
}
// draw fps
void drawInfo(){
if(fpsTimer.needsDisplay()){
float fps = 1. / fpsTimer.avg();
fpsTimer.updateLastDisplay();
sprintf(infoString, "%06.1f fps - Current object : %s", fps,
MyScene.object->getName().c_str());
MyScene.update();
}
int i = 0;
while(infoString[i] != '\0'){
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, infoString[i++]);
}
}
// display
clock_t ticks;
void display(void) {
glPushAttrib(GL_ALL_ATTRIB_BITS);
// Effacer tout
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // la couleur et le z
drawInfo();
glLoadIdentity(); // repere camera
if(isDrawingTexture || isRealtimeRaytracing){
const static GLdouble viewport[] = {
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
-2,-2,-4, 1
};
glMultMatrixd(viewport);
drawTexture(activeTexIndex);
// reset view
glLoadIdentity();
tbVisuTransform();
// swap buffers; draw on back buffer
if (isRealtimeRaytracing){
clock_t start = clock();
startRayTracing(!activeTexIndex, false);
ticks = clock() - start;
activeTexIndex = !activeTexIndex;
} else {
if (needRebuild == true){
int millis = (int)(ticks * 1000. / CLOCKS_PER_SEC);
long long expected = millis;
expected *= RAYTRACE_RES_X / PREVIEW_RES_X;
expected *= RAYTRACE_RES_Y / PREVIEW_RES_Y;
expected *= MSAA / PREVIEW_MSAA;
expected *= MSAA / PREVIEW_MSAA;
// expected /= THREADS; only for mac!
if (expected < 1000)
printf("will take %d milliseconds\n", (int)expected);
else if (expected < 1000 * 60)
printf("will take %d seconds\n", (int)(expected / 1000));
else if (expected < 1000 * 60 * 60)
printf("will take %d minutes\n", (int)(expected / 1000 / 60));
else if (expected < 1000 * 60 * 60 * 24) {
printf("RENDERING WILL TAKE LONG!\n");
printf("will take %d hour\n", (int)(expected / 1000 / 60 / 60));
} else if (expected < (long long)1000 * 60 * 60 * 24 * 365) {
printf("RENDERING WILL TAKE VERY LONG!\n");
printf("will take %d days\n", (int)(expected / 1000 / 60 / 60 / 24));
}
else if (expected < (long long)1000 * 60 * 60 * 24 * 365 * 1000) {
printf("RENDERING will take years!\n");
printf("will take %d year\n", (int)(expected / 1000 / 60 / 60 / 24 / 365 / 1000));
}
else if (expected < (long long)1000 * 60 * 60 * 24 * 365 * 1000 * 1000) {
printf("RENDERING will take thousands of years!\n");
printf("will take %d millenia\n", (int)(expected / 1000 / 60 / 60 / 24 / 365 / 1000 / 1000));
}
else if (expected < (long long)1000 * 60 * 60 * 24 * 365 * 1000 * 1000) {
printf("RENDERING will take millions of years!\n");
printf("will take %d million years\n", (int)(expected / 1000 / 60 / 60 / 24 / 365 / 1000 / 1000));
}
else if (expected < (float)1000 * 60 * 60 * 24 * 365 * 1000 * 1000 * 1000) {
printf("If the dinosaurs were alive when you started rendering, it would be ready now.\n");
printf("will take %d billion years\n", (int)(expected / 1000 / 60 / 60 / 24 / 365 / 1000 / 100));
}
else {
printf("THIS IS MADNESS!\n");
printf("will take %s seconds\n", "<overflow error>");
}
startRayTracing(activeTexIndex, true);
needRebuild = false;
}
}
} else {
tbVisuTransform(); // origine et orientation de la scene
MyScene.draw();
if (g_debug)
MyScene.debugDraw();
}
glutSwapBuffers();
glPopAttrib();
}
// pour changement de taille ou desiconification
void reshape(int w, int h){
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//glOrtho (-1.1, 1.1, -1.1,1.1, -1000.0, 1000.0);
gluPerspective(50, (float)w / h, 1, 10);
glMatrixMode(GL_MODELVIEW);
}
// prise en compte du clavier
void keyboard(unsigned char key, int x, int y){
cout << "down " << key << endl;
switch(key){
case 't':
cout << "Deprecated, 'b' toggles raytracing" << endl;
isDrawingTexture = 0;
isRealtimeRaytracing = 0;
break;
case 'L':
MyCameraPosition = getCameraPosition();
MyScene.addLightPoint(MyCameraPosition);
break;
case 'l':
MyScene.lights[0] = getCameraPosition();
break;
case 'r':
needRebuild = true;
isDrawingTexture = 1;
isRealtimeRaytracing = 0;
break;
case 'b':
if(isRealtimeRaytracing){
isDrawingTexture = 0;
isRealtimeRaytracing = 0;
}else{
cout << "Using " << THREADS << " threads and resolution of "
<< PREVIEW_RES_X << "x" << PREVIEW_RES_Y << endl;
isRealtimeRaytracing = 1;
isDrawingTexture = 0;
}
break;
case 27: // touche ESC
exit(0);
default:
if(!yourKeyboardPress(key, x, y)){
printf("Unknown key %c\n", key);
}
break;
}
}
void keyup(unsigned char key, int x, int y) {
cout << "up " << key << endl;
yourKeyboardRelease(key, x, y);
}
<commit_msg>Increased view window range.<commit_after>#include <cstdlib>
#include <cmath>
#include <ctime>
#include <GL/glut.h>
#include <assert.h>
#include <cstdlib>
#include "main.hpp"
#include "Scene.hpp"
// don't define anything in headers! only declare it!!!1!one!
Vec3Df MyCameraPosition;
// double buffered
unsigned int textures[2];
unsigned int activeTexIndex = 0;
unsigned int isDrawingTexture = 0;
unsigned int isRealtimeRaytracing = 0;
Tree MyTree;
Scene MyScene;
// options
extern bool g_phong;
extern bool g_checkerboard;
extern bool g_debug;
bool needRebuild = false; // if the raytrace needs to be built
/**
* draw a full-screen texture
*/
void drawTexture(int texIndex){
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textures[texIndex]);
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex3f(0, 0, 0);
glTexCoord2f(1, 0);
glVertex3f(4, 0, 0);
glTexCoord2f(1, 1);
glVertex3f(4, 4, 0);
glTexCoord2f(0, 1);
glVertex3f(0, 4, 0);
glEnd();
}
void animate() {
MyCameraPosition = getCameraPosition();
glutPostRedisplay();
}
void display(void);
void reshape(int w, int h);
void keyboard(unsigned char key, int x, int y);
// entry point
int main(int argc, char** argv){
glutInit(&argc, argv);
// couches du framebuffer utilisees par l'application
glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
// position et taille de la fenetre
glutInitWindowPosition(200, 100);
glutInitWindowSize(WINDOW_RES_X, WINDOW_RES_Y);
glutCreateWindow(argv[0]);
// Initialisation du point de vue
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0, 0, -4);
glRotatef(0, -1, 1, 1);
tbInitTransform(); // initialisation du point de vue
tbHelp(); // affiche l'aide sur la traqueboule
MyCameraPosition = getCameraPosition();
//
// Active la lumière
// Pour la partie
// ECLAIRAGE
glEnable( GL_LIGHTING);
glEnable( GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
int LightPos[4] = {0, 0, 3, 1};
glLightiv(GL_LIGHT0, GL_POSITION, LightPos);
//glMaterialiv(GL_FRONT_AND_BACK,GL_SPECULAR,MatSpec);
//glMateriali(GL_FRONT_AND_BACK,GL_SHININESS,10);
glEnable(GL_NORMALIZE);
glClearColor(0.0, 0.0, 0.0, 0.0);
// Details sur le mode de tracé
glEnable( GL_DEPTH_TEST); // effectuer le test de profondeur
//glEnable(GL_CULL_FACE);
//glCullFace(GL_BACK);
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_LINE);
glShadeModel(GL_SMOOTH);
// init textures
char* buf = new char[1024 * 1024 * 3];
glGenTextures(2, textures);
// texture 1
glBindTexture(GL_TEXTURE_2D, textures[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1024, 1024, 0, GL_RGB,
GL_UNSIGNED_BYTE, buf);
// texture 2
glBindTexture(GL_TEXTURE_2D, textures[1]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1024, 1024, 0, GL_RGB,
GL_UNSIGNED_BYTE, buf);
delete[] buf;
// cablage des callback
glutReshapeFunc(reshape);
glutSetKeyRepeat(true);
glutKeyboardFunc(keyboard);
glutKeyboardUpFunc(keyup);
glutDisplayFunc(display);
glutMouseFunc(tbMouseFunc); // traqueboule utilise la souris
glutMotionFunc(tbMotionFunc); // traqueboule utilise la souris
glutIdleFunc(animate);
int ret = init(argc, argv);
if(ret == 255)
return 0;
if(ret > 0)
return ret;
// lancement de la boucle principale
glutMainLoop();
return 0; // instruction jamais exécutée
}
// draw fps
void drawInfo(){
if(fpsTimer.needsDisplay()){
float fps = 1. / fpsTimer.avg();
fpsTimer.updateLastDisplay();
sprintf(infoString, "%06.1f fps - Current object : %s", fps,
MyScene.object->getName().c_str());
MyScene.update();
}
int i = 0;
while(infoString[i] != '\0'){
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, infoString[i++]);
}
}
// display
clock_t ticks;
void display(void) {
glPushAttrib(GL_ALL_ATTRIB_BITS);
// Effacer tout
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // la couleur et le z
drawInfo();
glLoadIdentity(); // repere camera
if(isDrawingTexture || isRealtimeRaytracing){
const static GLdouble viewport[] = {
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
-2,-2,-4, 1
};
glMultMatrixd(viewport);
drawTexture(activeTexIndex);
// reset view
glLoadIdentity();
tbVisuTransform();
// swap buffers; draw on back buffer
if (isRealtimeRaytracing){
clock_t start = clock();
startRayTracing(!activeTexIndex, false);
ticks = clock() - start;
activeTexIndex = !activeTexIndex;
} else {
if (needRebuild == true){
int millis = (int)(ticks * 1000. / CLOCKS_PER_SEC);
long long expected = millis;
expected *= RAYTRACE_RES_X / PREVIEW_RES_X;
expected *= RAYTRACE_RES_Y / PREVIEW_RES_Y;
expected *= MSAA / PREVIEW_MSAA;
expected *= MSAA / PREVIEW_MSAA;
// expected /= THREADS; only for mac!
if (expected < 1000)
printf("will take %d milliseconds\n", (int)expected);
else if (expected < 1000 * 60)
printf("will take %d seconds\n", (int)(expected / 1000));
else if (expected < 1000 * 60 * 60)
printf("will take %d minutes\n", (int)(expected / 1000 / 60));
else if (expected < 1000 * 60 * 60 * 24) {
printf("RENDERING WILL TAKE LONG!\n");
printf("will take %d hour\n", (int)(expected / 1000 / 60 / 60));
} else if (expected < (long long)1000 * 60 * 60 * 24 * 365) {
printf("RENDERING WILL TAKE VERY LONG!\n");
printf("will take %d days\n", (int)(expected / 1000 / 60 / 60 / 24));
}
else if (expected < (long long)1000 * 60 * 60 * 24 * 365 * 1000) {
printf("RENDERING will take years!\n");
printf("will take %d year\n", (int)(expected / 1000 / 60 / 60 / 24 / 365 / 1000));
}
else if (expected < (long long)1000 * 60 * 60 * 24 * 365 * 1000 * 1000) {
printf("RENDERING will take thousands of years!\n");
printf("will take %d millenia\n", (int)(expected / 1000 / 60 / 60 / 24 / 365 / 1000 / 1000));
}
else if (expected < (long long)1000 * 60 * 60 * 24 * 365 * 1000 * 1000) {
printf("RENDERING will take millions of years!\n");
printf("will take %d million years\n", (int)(expected / 1000 / 60 / 60 / 24 / 365 / 1000 / 1000));
}
else if (expected < (float)1000 * 60 * 60 * 24 * 365 * 1000 * 1000 * 1000) {
printf("If the dinosaurs were alive when you started rendering, it would be ready now.\n");
printf("will take %d billion years\n", (int)(expected / 1000 / 60 / 60 / 24 / 365 / 1000 / 100));
}
else {
printf("THIS IS MADNESS!\n");
printf("will take %s seconds\n", "<overflow error>");
}
startRayTracing(activeTexIndex, true);
needRebuild = false;
}
}
} else {
tbVisuTransform(); // origine et orientation de la scene
MyScene.draw();
if (g_debug)
MyScene.debugDraw();
}
glutSwapBuffers();
glPopAttrib();
}
// pour changement de taille ou desiconification
void reshape(int w, int h){
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//glOrtho (-1.1, 1.1, -1.1,1.1, -1000.0, 1000.0);
gluPerspective(50, (float)w / h, 1, 1000);
glMatrixMode(GL_MODELVIEW);
}
// prise en compte du clavier
void keyboard(unsigned char key, int x, int y){
cout << "down " << key << endl;
switch(key){
case 't':
cout << "Deprecated, 'b' toggles raytracing" << endl;
isDrawingTexture = 0;
isRealtimeRaytracing = 0;
break;
case 'L':
MyCameraPosition = getCameraPosition();
MyScene.addLightPoint(MyCameraPosition);
break;
case 'l':
MyScene.lights[0] = getCameraPosition();
break;
case 'r':
needRebuild = true;
isDrawingTexture = 1;
isRealtimeRaytracing = 0;
break;
case 'b':
if(isRealtimeRaytracing){
isDrawingTexture = 0;
isRealtimeRaytracing = 0;
}else{
cout << "Using " << THREADS << " threads and resolution of "
<< PREVIEW_RES_X << "x" << PREVIEW_RES_Y << endl;
isRealtimeRaytracing = 1;
isDrawingTexture = 0;
}
break;
case 27: // touche ESC
exit(0);
default:
if(!yourKeyboardPress(key, x, y)){
printf("Unknown key %c\n", key);
}
break;
}
}
void keyup(unsigned char key, int x, int y) {
cout << "up " << key << endl;
yourKeyboardRelease(key, x, y);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Michael X. Grey <[email protected]>
*
* Georgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <[email protected]> <[email protected]>
*
* This file is provided under the following "BSD-style" 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.
* 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 <osgGA/GUIEventAdapter>
#include "osgDart/DefaultEventHandler.h"
#include "osgDart/MouseEventHandler.h"
#include "osgDart/Viewer.h"
#include "osgDart/render/ShapeNode.h"
#include "osgDart/EntityNode.h"
#include "osgDart/utils.h"
#include "dart/dynamics/Entity.h"
#include <iostream>
namespace osgDart
{
DefaultEventHandler::DefaultEventHandler(Viewer* _viewer)
: mViewer(_viewer),
mLastCursorPosition(Eigen::Vector2d::Zero()),
mLastModKeyMask(0)
{
mViewer->addInstructionText("Spacebar: Turn simulation on/off for any active worlds\n");
mViewer->addInstructionText("Ctrl+H: Turn headlights on/off\n");
for(size_t i=0; i<NUM_MOUSE_BUTTONS; ++i)
for(size_t j=0; j<BUTTON_NOTHING; ++j)
mSuppressButtonPicks[i][j] = false;
mSuppressMovePicks = false;
clearButtonEvents();
}
//==============================================================================
DefaultEventHandler::~DefaultEventHandler()
{
// Do nothing
}
//==============================================================================
MouseButtonEvent DefaultEventHandler::getButtonEvent(MouseButton button) const
{
return mLastButtonEvent[button];
}
//==============================================================================
int DefaultEventHandler::getModKeyMask() const
{
return mLastModKeyMask;
}
//==============================================================================
double DefaultEventHandler::getWindowCursorX() const
{
return mLastCursorPosition[0];
}
//==============================================================================
double DefaultEventHandler::getWindowCursorY() const
{
return mLastCursorPosition[1];
}
//==============================================================================
Eigen::Vector3d DefaultEventHandler::getDeltaCursor(
const Eigen::Vector3d& _fromPosition,
ConstraintType _constraint,
const Eigen::Vector3d& _constraintVector) const
{
osg::Vec3d eye, center, up;
mViewer->getCamera()->getViewMatrixAsLookAt(eye, center, up);
Eigen::Vector3d near, far;
getNearAndFarPointUnderCursor(near, far);
Eigen::Vector3d v1 = far-near;
if(LINE_CONSTRAINT == _constraint)
{
const Eigen::Vector3d& b1 = near;
const Eigen::Vector3d& v2 = _constraintVector;
const Eigen::Vector3d& b2 = _fromPosition;
double v1_v1 = v1.dot(v1);
double v2_v2 = v2.dot(v2);
double v2_v1 = v2.dot(v1);
double denominator = v1_v1*v2_v2 - v2_v1*v2_v1;
double s;
if(fabs(denominator) < 1e-10)
s = 0;
else
s = (v1_v1*(v2.dot(b1)-v2.dot(b2)) + v2_v1*(v1.dot(b2)-v1.dot(b1)))/denominator;
return v2*s;
}
else if(PLANE_CONSTRAINT == _constraint)
{
const Eigen::Vector3d& n = _constraintVector;
double s = n.dot(_fromPosition - near) / n.dot(v1);
return near - _fromPosition + s*v1;
}
else
{
Eigen::Vector3d n = osgToEigVec3(center - eye);
double s = n.dot(_fromPosition - near) / n.dot(v1);
return near - _fromPosition + s*v1;
}
return Eigen::Vector3d::Zero();
}
//==============================================================================
void DefaultEventHandler::getNearAndFarPointUnderCursor(Eigen::Vector3d& near,
Eigen::Vector3d& far,
double distance) const
{
osg::Camera* C = mViewer->getCamera();
osg::Matrix VPW = C->getViewMatrix() * C->getProjectionMatrix()
* C->getViewport()->computeWindowMatrix();
osg::Matrix invVPW;
invVPW.invert(VPW);
double x = getWindowCursorX(), y = getWindowCursorY();
osg::Vec3 osgNear = osg::Vec3(x,y,0.0) * invVPW;
osg::Vec3 osgFar = osg::Vec3(x,y,distance) * invVPW;
near = osgToEigVec3(osgNear);
far = osgToEigVec3(osgFar);
}
//==============================================================================
const std::vector<PickInfo>& DefaultEventHandler::getButtonPicks(
MouseButton button, MouseButtonEvent event) const
{
if(BUTTON_NOTHING == event)
return mMovePicks;
return mButtonPicks[button][event];
}
//==============================================================================
const std::vector<PickInfo>& DefaultEventHandler::getMovePicks() const
{
return mMovePicks;
}
//==============================================================================
void DefaultEventHandler::suppressButtonPicks(MouseButton button,
MouseButtonEvent event)
{
if(BUTTON_NOTHING == event)
mSuppressMovePicks = true;
else
mSuppressButtonPicks[button][event] = true;
}
//==============================================================================
void DefaultEventHandler::suppressMovePicks()
{
mSuppressMovePicks = true;
}
//==============================================================================
void DefaultEventHandler::activateButtonPicks(MouseButton button,
MouseButtonEvent event)
{
if(BUTTON_NOTHING == event)
mSuppressMovePicks = false;
else
mSuppressButtonPicks[button][event] = false;
}
//==============================================================================
void DefaultEventHandler::activateMovePicks()
{
mSuppressMovePicks = false;
}
//==============================================================================
void DefaultEventHandler::pick(std::vector<PickInfo>& infoVector,
const osgGA::GUIEventAdapter& ea)
{
osgUtil::LineSegmentIntersector::Intersections hlist;
infoVector.clear();
if(mViewer->computeIntersections(ea, hlist))
{
infoVector.reserve(hlist.size());
for(const osgUtil::LineSegmentIntersector::Intersection& intersect : hlist)
{
osg::Drawable* drawable = intersect.drawable;
render::ShapeNode* shape =
dynamic_cast<render::ShapeNode*>(drawable->getParent(0));
if(shape)
{
PickInfo info;
info.shape = shape->getShape();
info.entity = shape->getParentEntityNode()->getEntity();
info.normal = osgToEigVec3(intersect.getWorldIntersectNormal());
info.position = osgToEigVec3(intersect.getWorldIntersectPoint());
infoVector.push_back(info);
}
}
}
}
//==============================================================================
void DefaultEventHandler::addMouseEventHandler(MouseEventHandler* handler)
{
mMouseEventHandlers.insert(handler);
handler->mEventHandler = this;
handler->addSubject(this);
}
//==============================================================================
const std::set<MouseEventHandler*>&
DefaultEventHandler::getMouseEventHandlers() const
{
return mMouseEventHandlers;
}
//==============================================================================
static bool wasActive(MouseButtonEvent event)
{
return ( (event == BUTTON_PUSH) || (event == BUTTON_DRAG) );
}
//==============================================================================
static void assignEventToButtons(
MouseButtonEvent (&mLastButtonEvent)[NUM_MOUSE_BUTTONS],
const osgGA::GUIEventAdapter& ea)
{
MouseButtonEvent event = BUTTON_NOTHING;
if(ea.getEventType() == osgGA::GUIEventAdapter::PUSH)
event = BUTTON_PUSH;
else if(ea.getEventType() == osgGA::GUIEventAdapter::DRAG)
event = BUTTON_DRAG;
else if(ea.getEventType() == osgGA::GUIEventAdapter::RELEASE)
event = BUTTON_RELEASE;
if(BUTTON_RELEASE == event)
{
if( (ea.getButtonMask() & osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON) == 0
&& wasActive(mLastButtonEvent[LEFT_MOUSE]) )
mLastButtonEvent[LEFT_MOUSE] = event;
if( (ea.getButtonMask() & osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON) == 0
&& wasActive(mLastButtonEvent[RIGHT_MOUSE]) )
mLastButtonEvent[RIGHT_MOUSE] = event;
if( (ea.getButtonMask() & osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON) == 0
&& wasActive(mLastButtonEvent[MIDDLE_MOUSE]) )
mLastButtonEvent[MIDDLE_MOUSE] = event;
}
else
{
if(ea.getButtonMask() & osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON)
mLastButtonEvent[LEFT_MOUSE] = event;
if(ea.getButtonMask() & osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON)
mLastButtonEvent[RIGHT_MOUSE] = event;
if(ea.getButtonMask() & osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON)
mLastButtonEvent[MIDDLE_MOUSE] = event;
}
}
//==============================================================================
bool DefaultEventHandler::handle(const osgGA::GUIEventAdapter& ea,
osgGA::GUIActionAdapter&)
{
mLastModKeyMask = ea.getModKeyMask();
switch(ea.getEventType())
{
case osgGA::GUIEventAdapter::PUSH:
case osgGA::GUIEventAdapter::DRAG:
case osgGA::GUIEventAdapter::RELEASE:
case osgGA::GUIEventAdapter::MOVE:
mLastCursorPosition[0] = ea.getX();
mLastCursorPosition[1] = ea.getY();
break;
default:
break;
}
switch(ea.getEventType())
{
case osgGA::GUIEventAdapter::KEYDOWN:
{
switch(ea.getKey())
{
case 8: // ctrl+h
{
mViewer->switchHeadlights(!mViewer->checkHeadlights());
return true;
break;
}
case ' ':
{
mViewer->simulate(!mViewer->isSimulating());
return true;
break;
}
}
}
case osgGA::GUIEventAdapter::MOVE:
{
if(!mSuppressMovePicks)
pick(mMovePicks, ea);
triggerMouseEventHandlers();
break;
}
case osgGA::GUIEventAdapter::PUSH:
case osgGA::GUIEventAdapter::DRAG:
case osgGA::GUIEventAdapter::RELEASE:
assignEventToButtons(mLastButtonEvent, ea);
eventPick(ea);
mViewer->updateDragAndDrops();
triggerMouseEventHandlers();
break;
default:
break;
}
return false;
}
//==============================================================================
void DefaultEventHandler::triggerMouseEventHandlers()
{
for(MouseEventHandler* h : mMouseEventHandlers)
{
h->update();
}
}
//==============================================================================
void DefaultEventHandler::eventPick(const osgGA::GUIEventAdapter& ea)
{
MouseButtonEvent mbe;
switch(ea.getEventType())
{
case osgGA::GUIEventAdapter::PUSH:
mbe = BUTTON_PUSH;
break;
case osgGA::GUIEventAdapter::DRAG:
mbe = BUTTON_DRAG;
break;
case osgGA::GUIEventAdapter::RELEASE:
mbe = BUTTON_RELEASE;
break;
default:
return;
}
if( ( (ea.getButtonMask() & osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON)
&& !mSuppressButtonPicks[LEFT_MOUSE][mbe])
|| ( (ea.getButtonMask() & osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON)
&& !mSuppressButtonPicks[RIGHT_MOUSE][mbe])
|| ( (ea.getButtonMask() & osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON)
&& !mSuppressButtonPicks[MIDDLE_MOUSE][mbe]))
{
pick(mTempPicks, ea);
if(ea.getButtonMask() & osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON)
mButtonPicks[LEFT_MOUSE][mbe] = mTempPicks;
if(ea.getButtonMask() & osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON)
mButtonPicks[RIGHT_MOUSE][mbe] = mTempPicks;
if(ea.getButtonMask() & osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON)
mButtonPicks[MIDDLE_MOUSE][mbe] = mTempPicks;
}
}
//==============================================================================
void DefaultEventHandler::clearButtonEvents()
{
for(size_t i=0; i<NUM_MOUSE_BUTTONS; ++i)
mLastButtonEvent[i] = BUTTON_NOTHING;
}
//==============================================================================
void DefaultEventHandler::handleDestructionNotification(
const dart::common::Subject* _subject)
{
MouseEventHandler* meh = const_cast<MouseEventHandler*>(
dynamic_cast<const MouseEventHandler*>(_subject));
std::set<MouseEventHandler*>::iterator it = mMouseEventHandlers.find(meh);
if(it != mMouseEventHandlers.end())
mMouseEventHandlers.erase(it);
}
} // namespace osgDart
<commit_msg>don't block spacebar when simulation is disabled<commit_after>/*
* Copyright (c) 2015, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Michael X. Grey <[email protected]>
*
* Georgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <[email protected]> <[email protected]>
*
* This file is provided under the following "BSD-style" 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.
* 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 <osgGA/GUIEventAdapter>
#include "osgDart/DefaultEventHandler.h"
#include "osgDart/MouseEventHandler.h"
#include "osgDart/Viewer.h"
#include "osgDart/render/ShapeNode.h"
#include "osgDart/EntityNode.h"
#include "osgDart/utils.h"
#include "dart/dynamics/Entity.h"
#include <iostream>
namespace osgDart
{
DefaultEventHandler::DefaultEventHandler(Viewer* _viewer)
: mViewer(_viewer),
mLastCursorPosition(Eigen::Vector2d::Zero()),
mLastModKeyMask(0)
{
mViewer->addInstructionText("Spacebar: Turn simulation on/off for any active worlds\n");
mViewer->addInstructionText("Ctrl+H: Turn headlights on/off\n");
for(size_t i=0; i<NUM_MOUSE_BUTTONS; ++i)
for(size_t j=0; j<BUTTON_NOTHING; ++j)
mSuppressButtonPicks[i][j] = false;
mSuppressMovePicks = false;
clearButtonEvents();
}
//==============================================================================
DefaultEventHandler::~DefaultEventHandler()
{
// Do nothing
}
//==============================================================================
MouseButtonEvent DefaultEventHandler::getButtonEvent(MouseButton button) const
{
return mLastButtonEvent[button];
}
//==============================================================================
int DefaultEventHandler::getModKeyMask() const
{
return mLastModKeyMask;
}
//==============================================================================
double DefaultEventHandler::getWindowCursorX() const
{
return mLastCursorPosition[0];
}
//==============================================================================
double DefaultEventHandler::getWindowCursorY() const
{
return mLastCursorPosition[1];
}
//==============================================================================
Eigen::Vector3d DefaultEventHandler::getDeltaCursor(
const Eigen::Vector3d& _fromPosition,
ConstraintType _constraint,
const Eigen::Vector3d& _constraintVector) const
{
osg::Vec3d eye, center, up;
mViewer->getCamera()->getViewMatrixAsLookAt(eye, center, up);
Eigen::Vector3d near, far;
getNearAndFarPointUnderCursor(near, far);
Eigen::Vector3d v1 = far-near;
if(LINE_CONSTRAINT == _constraint)
{
const Eigen::Vector3d& b1 = near;
const Eigen::Vector3d& v2 = _constraintVector;
const Eigen::Vector3d& b2 = _fromPosition;
double v1_v1 = v1.dot(v1);
double v2_v2 = v2.dot(v2);
double v2_v1 = v2.dot(v1);
double denominator = v1_v1*v2_v2 - v2_v1*v2_v1;
double s;
if(fabs(denominator) < 1e-10)
s = 0;
else
s = (v1_v1*(v2.dot(b1)-v2.dot(b2)) + v2_v1*(v1.dot(b2)-v1.dot(b1)))/denominator;
return v2*s;
}
else if(PLANE_CONSTRAINT == _constraint)
{
const Eigen::Vector3d& n = _constraintVector;
double s = n.dot(_fromPosition - near) / n.dot(v1);
return near - _fromPosition + s*v1;
}
else
{
Eigen::Vector3d n = osgToEigVec3(center - eye);
double s = n.dot(_fromPosition - near) / n.dot(v1);
return near - _fromPosition + s*v1;
}
return Eigen::Vector3d::Zero();
}
//==============================================================================
void DefaultEventHandler::getNearAndFarPointUnderCursor(Eigen::Vector3d& near,
Eigen::Vector3d& far,
double distance) const
{
osg::Camera* C = mViewer->getCamera();
osg::Matrix VPW = C->getViewMatrix() * C->getProjectionMatrix()
* C->getViewport()->computeWindowMatrix();
osg::Matrix invVPW;
invVPW.invert(VPW);
double x = getWindowCursorX(), y = getWindowCursorY();
osg::Vec3 osgNear = osg::Vec3(x,y,0.0) * invVPW;
osg::Vec3 osgFar = osg::Vec3(x,y,distance) * invVPW;
near = osgToEigVec3(osgNear);
far = osgToEigVec3(osgFar);
}
//==============================================================================
const std::vector<PickInfo>& DefaultEventHandler::getButtonPicks(
MouseButton button, MouseButtonEvent event) const
{
if(BUTTON_NOTHING == event)
return mMovePicks;
return mButtonPicks[button][event];
}
//==============================================================================
const std::vector<PickInfo>& DefaultEventHandler::getMovePicks() const
{
return mMovePicks;
}
//==============================================================================
void DefaultEventHandler::suppressButtonPicks(MouseButton button,
MouseButtonEvent event)
{
if(BUTTON_NOTHING == event)
mSuppressMovePicks = true;
else
mSuppressButtonPicks[button][event] = true;
}
//==============================================================================
void DefaultEventHandler::suppressMovePicks()
{
mSuppressMovePicks = true;
}
//==============================================================================
void DefaultEventHandler::activateButtonPicks(MouseButton button,
MouseButtonEvent event)
{
if(BUTTON_NOTHING == event)
mSuppressMovePicks = false;
else
mSuppressButtonPicks[button][event] = false;
}
//==============================================================================
void DefaultEventHandler::activateMovePicks()
{
mSuppressMovePicks = false;
}
//==============================================================================
void DefaultEventHandler::pick(std::vector<PickInfo>& infoVector,
const osgGA::GUIEventAdapter& ea)
{
osgUtil::LineSegmentIntersector::Intersections hlist;
infoVector.clear();
if(mViewer->computeIntersections(ea, hlist))
{
infoVector.reserve(hlist.size());
for(const osgUtil::LineSegmentIntersector::Intersection& intersect : hlist)
{
osg::Drawable* drawable = intersect.drawable;
render::ShapeNode* shape =
dynamic_cast<render::ShapeNode*>(drawable->getParent(0));
if(shape)
{
PickInfo info;
info.shape = shape->getShape();
info.entity = shape->getParentEntityNode()->getEntity();
info.normal = osgToEigVec3(intersect.getWorldIntersectNormal());
info.position = osgToEigVec3(intersect.getWorldIntersectPoint());
infoVector.push_back(info);
}
}
}
}
//==============================================================================
void DefaultEventHandler::addMouseEventHandler(MouseEventHandler* handler)
{
mMouseEventHandlers.insert(handler);
handler->mEventHandler = this;
handler->addSubject(this);
}
//==============================================================================
const std::set<MouseEventHandler*>&
DefaultEventHandler::getMouseEventHandlers() const
{
return mMouseEventHandlers;
}
//==============================================================================
static bool wasActive(MouseButtonEvent event)
{
return ( (event == BUTTON_PUSH) || (event == BUTTON_DRAG) );
}
//==============================================================================
static void assignEventToButtons(
MouseButtonEvent (&mLastButtonEvent)[NUM_MOUSE_BUTTONS],
const osgGA::GUIEventAdapter& ea)
{
MouseButtonEvent event = BUTTON_NOTHING;
if(ea.getEventType() == osgGA::GUIEventAdapter::PUSH)
event = BUTTON_PUSH;
else if(ea.getEventType() == osgGA::GUIEventAdapter::DRAG)
event = BUTTON_DRAG;
else if(ea.getEventType() == osgGA::GUIEventAdapter::RELEASE)
event = BUTTON_RELEASE;
if(BUTTON_RELEASE == event)
{
if( (ea.getButtonMask() & osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON) == 0
&& wasActive(mLastButtonEvent[LEFT_MOUSE]) )
mLastButtonEvent[LEFT_MOUSE] = event;
if( (ea.getButtonMask() & osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON) == 0
&& wasActive(mLastButtonEvent[RIGHT_MOUSE]) )
mLastButtonEvent[RIGHT_MOUSE] = event;
if( (ea.getButtonMask() & osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON) == 0
&& wasActive(mLastButtonEvent[MIDDLE_MOUSE]) )
mLastButtonEvent[MIDDLE_MOUSE] = event;
}
else
{
if(ea.getButtonMask() & osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON)
mLastButtonEvent[LEFT_MOUSE] = event;
if(ea.getButtonMask() & osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON)
mLastButtonEvent[RIGHT_MOUSE] = event;
if(ea.getButtonMask() & osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON)
mLastButtonEvent[MIDDLE_MOUSE] = event;
}
}
//==============================================================================
bool DefaultEventHandler::handle(const osgGA::GUIEventAdapter& ea,
osgGA::GUIActionAdapter&)
{
mLastModKeyMask = ea.getModKeyMask();
switch(ea.getEventType())
{
case osgGA::GUIEventAdapter::PUSH:
case osgGA::GUIEventAdapter::DRAG:
case osgGA::GUIEventAdapter::RELEASE:
case osgGA::GUIEventAdapter::MOVE:
mLastCursorPosition[0] = ea.getX();
mLastCursorPosition[1] = ea.getY();
break;
default:
break;
}
switch(ea.getEventType())
{
case osgGA::GUIEventAdapter::KEYDOWN:
{
switch(ea.getKey())
{
case 8: // ctrl+h
{
mViewer->switchHeadlights(!mViewer->checkHeadlights());
return true;
break;
}
case ' ':
{
if(mViewer->isAllowingSimulation())
{
mViewer->simulate(!mViewer->isSimulating());
return true;
}
break;
}
}
}
case osgGA::GUIEventAdapter::MOVE:
{
if(!mSuppressMovePicks)
pick(mMovePicks, ea);
triggerMouseEventHandlers();
break;
}
case osgGA::GUIEventAdapter::PUSH:
case osgGA::GUIEventAdapter::DRAG:
case osgGA::GUIEventAdapter::RELEASE:
assignEventToButtons(mLastButtonEvent, ea);
eventPick(ea);
mViewer->updateDragAndDrops();
triggerMouseEventHandlers();
break;
default:
break;
}
return false;
}
//==============================================================================
void DefaultEventHandler::triggerMouseEventHandlers()
{
for(MouseEventHandler* h : mMouseEventHandlers)
{
h->update();
}
}
//==============================================================================
void DefaultEventHandler::eventPick(const osgGA::GUIEventAdapter& ea)
{
MouseButtonEvent mbe;
switch(ea.getEventType())
{
case osgGA::GUIEventAdapter::PUSH:
mbe = BUTTON_PUSH;
break;
case osgGA::GUIEventAdapter::DRAG:
mbe = BUTTON_DRAG;
break;
case osgGA::GUIEventAdapter::RELEASE:
mbe = BUTTON_RELEASE;
break;
default:
return;
}
if( ( (ea.getButtonMask() & osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON)
&& !mSuppressButtonPicks[LEFT_MOUSE][mbe])
|| ( (ea.getButtonMask() & osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON)
&& !mSuppressButtonPicks[RIGHT_MOUSE][mbe])
|| ( (ea.getButtonMask() & osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON)
&& !mSuppressButtonPicks[MIDDLE_MOUSE][mbe]))
{
pick(mTempPicks, ea);
if(ea.getButtonMask() & osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON)
mButtonPicks[LEFT_MOUSE][mbe] = mTempPicks;
if(ea.getButtonMask() & osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON)
mButtonPicks[RIGHT_MOUSE][mbe] = mTempPicks;
if(ea.getButtonMask() & osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON)
mButtonPicks[MIDDLE_MOUSE][mbe] = mTempPicks;
}
}
//==============================================================================
void DefaultEventHandler::clearButtonEvents()
{
for(size_t i=0; i<NUM_MOUSE_BUTTONS; ++i)
mLastButtonEvent[i] = BUTTON_NOTHING;
}
//==============================================================================
void DefaultEventHandler::handleDestructionNotification(
const dart::common::Subject* _subject)
{
MouseEventHandler* meh = const_cast<MouseEventHandler*>(
dynamic_cast<const MouseEventHandler*>(_subject));
std::set<MouseEventHandler*>::iterator it = mMouseEventHandlers.find(meh);
if(it != mMouseEventHandlers.end())
mMouseEventHandlers.erase(it);
}
} // namespace osgDart
<|endoftext|> |
<commit_before>#include "compiler.h"
#include "mswin.h"
#include "resources.h"
#include "glinit.h"
#include "model.h"
#include "arguments.h"
#include "polymorph.h"
#include "settings.h"
#include "dialog.h"
#include "qpc.h"
#include <tchar.h>
#include <windowsx.h>
#include <cstdint>
NOINLINE int message_loop (HWND hdlg)
{
MSG msg;
while (::GetMessage (& msg, NULL, 0, 0)) {
if (! hdlg || ! ::IsDialogMessage (hdlg, & msg)) {
::TranslateMessage (& msg);
::DispatchMessage (& msg);
}
}
return (int) msg.wParam;
}
int WINAPI _tWinMain (HINSTANCE hInstance, HINSTANCE, LPTSTR, int)
{
if (! glinit (hInstance)) return 1;
LPCTSTR display_name;
::LoadString (hInstance, 1, (LPTSTR) (& display_name), 0);
ALIGNED16 window_struct_t ws;
arguments_t arguments (::GetCommandLine ());
ws.mode = arguments.mode;
load_settings (ws.settings);
// Create the screen saver window.
// Retry once on failure (works around sporadic SetPixelFormat
// failure observed on Intel integrated graphics on Windows 7).
register_class (hInstance);
HWND hwnd;
for (unsigned retries = 0; retries != 2; ++ retries) {
hwnd = create_window (hInstance, arguments.parent, display_name, & ws);
if (hwnd) break;
// Window creation failed (window will be destroyed).
// Pump messages and throw away the WM_QUIT.
message_loop (0);
}
if (! hwnd) return 1;
if (! ws.model.initialize (qpc ())) return 1;
// Create the configure dialog if in configure mode.
dialog_struct_t ds = { ws.settings, hwnd, };
HWND hdlg = arguments.mode == configure ? create_dialog (hInstance, & ds) : NULL;
// Show the main window, or the configure dialog if in configure mode.
::ShowWindow (hdlg ? hdlg : hwnd, SW_SHOW);
return message_loop (hdlg);
}
#ifdef TINY
// Tiny startup.
// No standard handles, window placement, environment variables,
// command-line transformation, global constructors and destructors,
// atexit functions, thread-local storage, runtime relocation fixups,
// 387 floating-point initialization, signal handlers and no exceptions.
extern "C"
{
// This symbol is defined by the linker.
extern IMAGE_DOS_HEADER __ImageBase;
// In the linker command line, specify this function as the entry point.
VISIBLE NORETURN ALIGN_STACK void custom_startup ()
{
HINSTANCE hInstance = (HINSTANCE) & __ImageBase;
int status = _tWinMain (hInstance, NULL, NULL, 0);
::ExitProcess ((UINT) (status));
}
}
#endif
<commit_msg>main.cpp: use SetWindowPos, not ShowWindow (otherwise, WM_WINDOWPOSCHANGING is not always received).<commit_after>#include "compiler.h"
#include "mswin.h"
#include "resources.h"
#include "glinit.h"
#include "model.h"
#include "arguments.h"
#include "polymorph.h"
#include "settings.h"
#include "dialog.h"
#include "qpc.h"
#include <tchar.h>
#include <windowsx.h>
#include <cstdint>
NOINLINE int message_loop (HWND hdlg)
{
MSG msg;
while (::GetMessage (& msg, NULL, 0, 0)) {
if (! hdlg || ! ::IsDialogMessage (hdlg, & msg)) {
::TranslateMessage (& msg);
::DispatchMessage (& msg);
}
}
return (int) msg.wParam;
}
int WINAPI _tWinMain (HINSTANCE hInstance, HINSTANCE, LPTSTR, int)
{
if (! glinit (hInstance)) return 1;
LPCTSTR display_name;
::LoadString (hInstance, 1, (LPTSTR) (& display_name), 0);
ALIGNED16 window_struct_t ws;
arguments_t arguments (::GetCommandLine ());
ws.mode = arguments.mode;
load_settings (ws.settings);
// Create the screen saver window.
// Retry once on failure (works around sporadic SetPixelFormat
// failure observed on Intel integrated graphics on Windows 7).
register_class (hInstance);
HWND hwnd;
for (unsigned retries = 0; retries != 2; ++ retries) {
hwnd = create_window (hInstance, arguments.parent, display_name, & ws);
if (hwnd) break;
// Window creation failed (window will be destroyed).
// Pump messages and throw away the WM_QUIT.
message_loop (0);
}
if (! hwnd) return 1;
if (! ws.model.initialize (qpc ())) return 1;
// Create the configure dialog if in configure mode.
dialog_struct_t ds = { ws.settings, hwnd, };
HWND hdlg = arguments.mode == configure ? create_dialog (hInstance, & ds) : NULL;
// Show the main window, or the configure dialog if in configure mode.
// We use SetWindowPos because on Windows XP when the main window is
// shown as a child of the screensaver control-panel applet windows,
// the WM_WINDOWPOSCHANGING doesn't arrive if we use ShowWindow.
::SetWindowPos (hdlg ? hdlg : hwnd, NULL, 0, 0, 0, 0,
SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_SHOWWINDOW);
return message_loop (hdlg);
}
#ifdef TINY
// Tiny startup.
// No standard handles, window placement, environment variables,
// command-line transformation, global constructors and destructors,
// atexit functions, thread-local storage, runtime relocation fixups,
// 387 floating-point initialization, signal handlers and no exceptions.
extern "C"
{
// This symbol is defined by the linker.
extern IMAGE_DOS_HEADER __ImageBase;
// In the linker command line, specify this function as the entry point.
VISIBLE NORETURN ALIGN_STACK void custom_startup ()
{
HINSTANCE hInstance = (HINSTANCE) & __ImageBase;
int status = _tWinMain (hInstance, NULL, NULL, 0);
::ExitProcess ((UINT) (status));
}
}
#endif
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.