<commit_before>#include "Riostream.h"
#include "TMatrixD.h"
#include "TVectorD.h"
#include "TGraphErrors.h"
#include "TDecompChol.h"
#include "TDecompSVD.h"
#include "TF1.h"

// This macro shows several ways to perform a linear least-squares
// analysis . To keep things simple we fit a straight line to 4
// data points
// The first 4 methods use the linear algebra package to find
//  x  such that min (A x - b)^T (A x - b) where A and b
//  are calculated with the data points  and the functional expression :
//
//  1. Normal equations:
//   Expanding the expression (A x - b)^T (A x - b) and taking the
//   derivative wrt x leads to the "Normal Equations":
//   A^T A x = A^T b  where A^T A is a positive definite matrix. Therefore,
//   a Cholesky decomposition scheme can be used to calculate its inverse .
//   This leads to the solution x = (A^T A)^-1 A^T b . All this is done in
//   routine NormalEqn . We made it a bit more complicated by giving the
//   data weights .
//   Numerically this is not the best way to proceed because effctively the
//   condition number of A^T A is twice as large as that of A, making inversion
//   more difficult
//
//  2. SVD
//   One can show that solving A x = b for x with A of size (m x n) and m > n
//   through a Singular Value Decomposition is equivalent to miminizing
//   (A x - b)^T (A x - b)
//   Numerically , this is the most stable method of all 5
//
//  3. Pseudo Inverse
//   Here we calulate the generalized matrix inverse ("pseudo inverse") by
//   solving A X = Unit for matrix X through an SVD . The formal expression for
//   is X = (A^T A)^-1 A^T . Then we multiply it by b .
//   Numerically, not as good as 2 and not as fast . In general it is not a
//   good idea to solve a set of linear equations with a matrix inversion .
//
//  4. Pseudo Inverse , brute force
//   The pseudo inverse is calculated brute force through a series of matrix
//   manipulations . It shows nicely some operations in the matrix package,
//   but is otherwise a big "no no" .
//
//  5. Least-squares analyisis with Minuit
//   An objective function L is minimized by Minuit, where
//    L = sum_i { (y - c_0 -c_1 * x / e)^2 }
//   Minuit will calculate numerically the derivative of L wrt c_0 and c_1 .
//   It has not been told that these derivatives are linear in the parameters
//   c_0 and c_1 .
//   For ill-conditioned linear problems it is better to use the fact it is
//   a linear fit as in 2 .
//
// Another interesting thing is the way we assign data to the vectors and
// matrices through adoption .
// This allows data assignment without physically moving bytes around .

void solveLinear(Double_t eps = 1.e-12)
{
  cout << "Perform the fit  y = c0 + c1 * x in four different ways" << endl;

  const Int_t nrVar  = 2;
  const Int_t nrPnts = 4;

  Double_t ax[] = {0.0,1.0,2.0,3.0};
  Double_t ay[] = {1.4,1.5,3.7,4.1};
  Double_t ae[] = {0.5,0.2,1.0,0.5};

  // Make the vectors 'Use" the data : they are not copied, the vector data
  // pointer is just set appropriately

  TVectorD x; x.Use(nrPnts,ax);
  TVectorD y; y.Use(nrPnts,ay);
  TVectorD e; e.Use(nrPnts,ae);

  TMatrixD A(nrPnts,nrVar);
  TMatrixDColumn(A,0) = 1.0;
  TMatrixDColumn(A,1) = x;

  cout << " - 1. solve through Normal Equations" << endl;

  const TVectorD c_norm = NormalEqn(A,y,e);

  cout << " - 2. solve through SVD" << endl;
  // numerically  preferred method

  // first bring the weights in place
  TMatrixD Aw = A;
  TVectorD yw = y;
  for (Int_t irow = 0; irow < A.GetNrows(); irow++) {
    TMatrixDRow(Aw,irow) *= 1/e(irow);
    yw(irow) /= e(irow);
  }

  TDecompSVD svd(Aw);
  Bool_t ok;
  const TVectorD c_svd = svd.Solve(yw,ok);

  cout << " - 3. solve with pseudo inverse" << endl;

  const TMatrixD pseudo1  = svd.Invert();
  TVectorD c_pseudo1 = yw;
  c_pseudo1 *= pseudo1;

  cout << " - 4. solve with pseudo inverse, calculated brute force" << endl;

  const TMatrixD pseudo2 = TMatrixD(TMatrixDBase::kAtA,Aw).Invert()*Aw.T();
  TVectorD c_pseudo2 = yw;
  c_pseudo2 *= pseudo2;

  cout << " - 5. Minuit through TGraph" << endl;

  TGraphErrors *gr = new TGraphErrors(nrPnts,ax,ay,0,ae);
  TF1 *f1 = new TF1("f1","pol1",0,5);
  gr->Fit("f1","Q");
  TVectorD c_graph(nrVar);
  c_graph(0) = f1->GetParameter(0);
  c_graph(1) = f1->GetParameter(1);

  // Check that all 4 answers are identical within a certain
  // tolerance . The 1e-12 is somewhat arbitrary . It turns out that
  // the TGraph fit is different by a few times 1e-13.

  Bool_t same = kTRUE;
  same &= VerifyVectorIdentity(c_norm,c_svd,0,eps);
  same &= VerifyVectorIdentity(c_norm,c_pseudo1,0,eps);
  same &= VerifyVectorIdentity(c_norm,c_pseudo2,0,eps);
  same &= VerifyVectorIdentity(c_norm,c_graph,0,eps);
  if (same)
    cout << " All solutions are the same within tolerance of " << eps << endl;
  else
    cout << " Some solutions differ more than the allowed tolerance of " << eps << endl;
}
<commit_msg>Fix typo in comments<commit_after>#include "Riostream.h"
#include "TMatrixD.h"
#include "TVectorD.h"
#include "TGraphErrors.h"
#include "TDecompChol.h"
#include "TDecompSVD.h"
#include "TF1.h"

// This macro shows several ways to perform a linear least-squares
// analysis . To keep things simple we fit a straight line to 4
// data points
// The first 4 methods use the linear algebra package to find
//  x  such that min (A x - b)^T (A x - b) where A and b
//  are calculated with the data points  and the functional expression :
//
//  1. Normal equations:
//   Expanding the expression (A x - b)^T (A x - b) and taking the
//   derivative wrt x leads to the "Normal Equations":
//   A^T A x = A^T b  where A^T A is a positive definite matrix. Therefore,
//   a Cholesky decomposition scheme can be used to calculate its inverse .
//   This leads to the solution x = (A^T A)^-1 A^T b . All this is done in
//   routine NormalEqn . We made it a bit more complicated by giving the
//   data weights .
//   Numerically this is not the best way to proceed because effctively the
//   condition number of A^T A is twice as large as that of A, making inversion
//   more difficult
//
//  2. SVD
//   One can show that solving A x = b for x with A of size (m x n) and m > n
//   through a Singular Value Decomposition is equivalent to miminizing
//   (A x - b)^T (A x - b)
//   Numerically , this is the most stable method of all 5
//
//  3. Pseudo Inverse
//   Here we calulate the generalized matrix inverse ("pseudo inverse") by
//   solving A X = Unit for matrix X through an SVD . The formal expression for
//   is X = (A^T A)^-1 A^T . Then we multiply it by b .
//   Numerically, not as good as 2 and not as fast . In general it is not a
//   good idea to solve a set of linear equations with a matrix inversion .
//
//  4. Pseudo Inverse , brute force
//   The pseudo inverse is calculated brute force through a series of matrix
//   manipulations . It shows nicely some operations in the matrix package,
//   but is otherwise a big "no no" .
//
//  5. Least-squares analysis with Minuit
//   An objective function L is minimized by Minuit, where
//    L = sum_i { (y - c_0 -c_1 * x / e)^2 }
//   Minuit will calculate numerically the derivative of L wrt c_0 and c_1 .
//   It has not been told that these derivatives are linear in the parameters
//   c_0 and c_1 .
//   For ill-conditioned linear problems it is better to use the fact it is
//   a linear fit as in 2 .
//
// Another interesting thing is the way we assign data to the vectors and
// matrices through adoption .
// This allows data assignment without physically moving bytes around .

void solveLinear(Double_t eps = 1.e-12)
{
  cout << "Perform the fit  y = c0 + c1 * x in four different ways" << endl;

  const Int_t nrVar  = 2;
  const Int_t nrPnts = 4;

  Double_t ax[] = {0.0,1.0,2.0,3.0};
  Double_t ay[] = {1.4,1.5,3.7,4.1};
  Double_t ae[] = {0.5,0.2,1.0,0.5};

  // Make the vectors 'Use" the data : they are not copied, the vector data
  // pointer is just set appropriately

  TVectorD x; x.Use(nrPnts,ax);
  TVectorD y; y.Use(nrPnts,ay);
  TVectorD e; e.Use(nrPnts,ae);

  TMatrixD A(nrPnts,nrVar);
  TMatrixDColumn(A,0) = 1.0;
  TMatrixDColumn(A,1) = x;

  cout << " - 1. solve through Normal Equations" << endl;

  const TVectorD c_norm = NormalEqn(A,y,e);

  cout << " - 2. solve through SVD" << endl;
  // numerically  preferred method

  // first bring the weights in place
  TMatrixD Aw = A;
  TVectorD yw = y;
  for (Int_t irow = 0; irow < A.GetNrows(); irow++) {
    TMatrixDRow(Aw,irow) *= 1/e(irow);
    yw(irow) /= e(irow);
  }

  TDecompSVD svd(Aw);
  Bool_t ok;
  const TVectorD c_svd = svd.Solve(yw,ok);

  cout << " - 3. solve with pseudo inverse" << endl;

  const TMatrixD pseudo1  = svd.Invert();
  TVectorD c_pseudo1 = yw;
  c_pseudo1 *= pseudo1;

  cout << " - 4. solve with pseudo inverse, calculated brute force" << endl;

  const TMatrixD pseudo2 = TMatrixD(TMatrixDBase::kAtA,Aw).Invert()*Aw.T();
  TVectorD c_pseudo2 = yw;
  c_pseudo2 *= pseudo2;

  cout << " - 5. Minuit through TGraph" << endl;

  TGraphErrors *gr = new TGraphErrors(nrPnts,ax,ay,0,ae);
  TF1 *f1 = new TF1("f1","pol1",0,5);
  gr->Fit("f1","Q");
  TVectorD c_graph(nrVar);
  c_graph(0) = f1->GetParameter(0);
  c_graph(1) = f1->GetParameter(1);

  // Check that all 4 answers are identical within a certain
  // tolerance . The 1e-12 is somewhat arbitrary . It turns out that
  // the TGraph fit is different by a few times 1e-13.

  Bool_t same = kTRUE;
  same &= VerifyVectorIdentity(c_norm,c_svd,0,eps);
  same &= VerifyVectorIdentity(c_norm,c_pseudo1,0,eps);
  same &= VerifyVectorIdentity(c_norm,c_pseudo2,0,eps);
  same &= VerifyVectorIdentity(c_norm,c_graph,0,eps);
  if (same)
    cout << " All solutions are the same within tolerance of " << eps << endl;
  else
    cout << " Some solutions differ more than the allowed tolerance of " << eps << endl;
}
<|endoftext|>


<commit_before>#include "Particle.h"

Particle::Particle():life(-1)
{
}

Particle::~Particle()
{
}

static double gravity = 0.4;

void Particle::update(int elapsed)
{
	life -= elapsed;
	x += speedX * elapsed;
	y += speedY * elapsed;

	speedY += gravity * elapsed / 1000;
}

int Particle::getX()
{
	return x;
}

int Particle::getY()
{
	return y;
}

COLORREF Particle::getColor()
{
	return color;
}

#include <stdlib.h>
#include <math.h>
#define PI 3.1415926
void Particle::reset(int positionX, int positionY, COLORREF color)
{
	x = positionX;
	y = positionY;
	this->color = color;

	life = rand() % 200 + 800;

	int velocity = rand()%30 + 150;

	int angle = rand() % 21+70;

	speedY = -sin(PI / 180 * angle) * velocity / 1000;
	speedX = cos(PI / 180 * angle) * velocity / 1000;

	int sign = rand()%2 ? 1 : -1;
	speedX = speedX * sign;
}

BOOL Particle::isAlive()
{
	return life > 0;
}
<commit_msg>add user preference manage<commit_after>#include "Particle.h"

Particle::Particle():life(-1)
{
}

Particle::~Particle()
{
}

static double gravity = 0.4;

void Particle::update(int elapsed)
{
	life -= elapsed;
	x += speedX * elapsed;
	y += speedY * elapsed;

	speedY += gravity * elapsed / 1000;
}

int Particle::getX()
{
	return x;
}

int Particle::getY()
{
	return y;
}

COLORREF Particle::getColor()
{
	return color;
}

#include <stdlib.h>
#include <math.h>
#define PI 3.1415926
void Particle::reset(int positionX, int positionY, COLORREF color)
{
	x = positionX;
	y = positionY;
	this->color = color;

	life = rand() % 200 + 800;

	int velocity = rand()%30 + 150;

	int angle = rand() % 21+70;

	speedY = -sin(PI / 180 * angle) * velocity / 1000;
	speedX = cos(PI / 180 * angle) * velocity / 1000;

	int sign = rand()%2 ? 1 : -1;
	speedX = speedX * sign;
}

BOOL Particle::isAlive()
{
	return life > 0;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkInteractorStyleFlight.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to John Biddiscombe of the Rutherford Appleton Laboratory
             who developed class.

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

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 REGENTS 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 "vtkInteractorStyleFlight.h"
#include "vtkMath.h"
#include "vtkCellPicker.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkObjectFactory.h"

//------------------------------------------------------------------------------
vtkInteractorStyleFlight* vtkInteractorStyleFlight::New()
{
  // irst try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkInteractorStyleFlight");
  if(ret)
    {
    return (vtkInteractorStyleFlight*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkInteractorStyleFlight;
}
//---------------------------------------------------------------------------
vtkInteractorStyleFlight::vtkInteractorStyleFlight()
{
  this->KeysDown     = 0;
  this->Flying       = 0;
  this->Reversing    = 0;
  this->TimerRunning = 0;
  this->DiagonalLength           = 1.0;
  this->MotionStepSize           = 1.0/250.0;
  this->MotionUserScale          = 1.0;  // +/- key adjustment
  this->MotionAccelerationFactor = 10.0;
  this->AngleStepSize            = 1.0;
  this->AngleAccelerationFactor  = 5.0;
  this->OldX = 0.0;
  this->OldY = 0.0;
}
//---------------------------------------------------------------------------
vtkInteractorStyleFlight::~vtkInteractorStyleFlight() {

}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::DoTimerStart(void) {
  if (this->TimerRunning) return;
  vtkRenderWindowInteractor *rwi = this->Interactor;
  rwi->CreateTimer(VTKI_TIMER_FIRST);
  this->TimerRunning = 1;
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::DoTimerStop(void) {
  if (!this->TimerRunning) return;
  vtkRenderWindowInteractor *rwi = this->Interactor;
  rwi->DestroyTimer();
  this->TimerRunning = 0;
}
//---------------------------------------------------------------------------
// Mouse event handlers
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnLeftButtonDown(int ctrl, int shift, int X, int Y) {
  this->UpdateInternalState(ctrl, shift, X, Y);
  if (!this->Reversing) {
      this->OldX        = this->x2 = X;
      this->OldY        = this->y2 = Y;
      this->YawAngle   = 0;
      this->PitchAngle = 0;
      this->DoTimerStart();
  }
  this->Flying       = 1;
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnLeftButtonUp(int ctrl, int shift, int X, int Y) {
  this->UpdateInternalState(ctrl, shift, X, Y);
  this->Flying       =  0;
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnRightButtonDown(int ctrl, int shift, int X, int Y) {
  this->UpdateInternalState(ctrl, shift, X, Y);
  if (!this->Flying) {
      this->OldX        = this->x2 = X;
      this->OldY        = this->y2 = Y;
      this->YawAngle   = 0;
      this->PitchAngle = 0;
      this->DoTimerStart();
  }
  this->Reversing    = 1;
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnRightButtonUp(int ctrl, int shift, int X, int Y) {
  this->UpdateInternalState(ctrl, shift, X, Y);
  this->Reversing    =  0;
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnMiddleButtonDown(int ctrl, int shift, int X, int Y) {
  this->UpdateInternalState(ctrl, shift, X, Y);
  // want to add some more functions???
  // I've got no middle mouse button :(
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnMiddleButtonUp(int ctrl, int shift, int X, int Y) {
  this->UpdateInternalState(ctrl, shift, X, Y);
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnMouseMove(int ctrl, int shift, int X, int Y) {
  this->UpdateInternalState(ctrl, shift, X, Y);
  if (Flying || Reversing) UpdateMouseSteering(X, Y);
}
//---------------------------------------------------------------------------
// Keyboard event handlers
// Note, OnChar is a key press down and then up event
// Note, OnKeyDown/OnKeyUp are more sensitive for controlling motion
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnChar(int ctrl, int shift,
                                char keycode, int vtkNotUsed(repeatcount))
{
  this->CtrlKey  = ctrl;
  this->ShiftKey = shift;
  switch (keycode)
    {
    // we are not overriding these keycodes
    case 'Q' :    case 'q' :
    case 'e' :    case 'E' :
    case 'u' :    case 'U' :
    case 'r' :    case 'R' :
    case 'w' :    case 'W' :
    case 's' :    case 'S' :
    case '3' :
    case 'p' :    case 'P' :
        vtkInteractorStyle::OnChar(ctrl, shift, keycode, 0);
        break;
    case '+' :
        this->MotionUserScale *= 2.0;
        break;
    case '-' :
        this->MotionUserScale *= 0.5;
        break;
    }
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnKeyDown(int ctrl, int shift,
                                char keycode, int vtkNotUsed(repeatcount))
{
  this->CtrlKey  = ctrl;
  this->ShiftKey = shift;
  // New light mode behaviour
  // Note that we'll need #defines for ARROW key defs under non win32 OS
#ifdef _WIN32
  switch (keycode)
    {
		case VK_LEFT  	: this->KeysDown |=1;  break;
		case VK_RIGHT 	: this->KeysDown |=2;  break;
		case VK_UP    	: this->KeysDown |=4;  break;
		case VK_DOWN  	: this->KeysDown |=8;  break;
		case 'a','A'	: this->KeysDown |=16; break;
		case 'z','Z' 	: this->KeysDown |=32; break;
    }
    // it may already be started but it doesn't matter
	if (KeysDown) this->DoTimerStart();
#endif
}

//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnKeyUp(int ctrl, int shift,
                                char keycode, int vtkNotUsed(repeatcount))
{
  this->CtrlKey  = ctrl;
  this->ShiftKey = shift;
#ifdef _WIN32
  switch (keycode) {
		case VK_LEFT  	: this->KeysDown &= ~1;  break;
		case VK_RIGHT 	: this->KeysDown &= ~2;  break;
		case VK_UP    	: this->KeysDown &= ~4;  break;
		case VK_DOWN  	: this->KeysDown &= ~8;  break;
		case 'a','A'	: this->KeysDown &= ~16; break;
		case 'z','Z' 	: this->KeysDown &= ~32; break;
	}
#endif
}
//---------------------------------------------------------------------------
// All actual motion is performed in the timer
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnTimer(void) {
    vtkRenderWindowInteractor *rwi = this->Interactor;
    // if we get a timer message we weren't expecting, just shut it down
	if (!Flying && !Reversing && !KeysDown) this->DoTimerStop();
	else {
        // Make sure CurrentCamera variable is initialized
        this->FindPokedCamera(this->OldX, this->OldY);
        this->SetupMotionVars();
        // Are we moving
        if (Flying || Reversing) FlyByMouse();
		if (KeysDown)            FlyByKey();
        // Tidy up Camera stuff
        this->CurrentCamera->OrthogonalizeViewUp();
        this->CurrentRenderer->ResetCameraClippingRange();
        // Make sure light follows camera if desired
        if (rwi->GetLightFollowCamera()) {
            this->CurrentLight->SetPosition(this->CurrentCamera->GetPosition());
            this->CurrentLight->SetFocalPoint(this->CurrentCamera->GetFocalPoint());
        }
        rwi->Render();
        rwi->CreateTimer(VTKI_TIMER_UPDATE);
	}
}
//---------------------------------------------------------------------------
// Calculate angles for next redraw in timer event
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::UpdateMouseSteering(int x, int y) {
	//
    double aspeed = this->AngleStepSize*(this->ShiftKey ? this->AngleAccelerationFactor : 1.0);
    //
    // we want to steer by an amount proportional to window viewangle and size
    vtkRenderWindowInteractor *rwi = this->Interactor;
    int *size = rwi->GetSize();
    double scalefactor = 5.0*this->CurrentCamera->GetViewAngle()/(double)size[0];
    double dx = - (x - this->OldX)*scalefactor;
    double dy =   (y - this->OldY)*scalefactor;
    this->YawAngle   = dx*aspeed;
    this->PitchAngle = dy*aspeed;
    this->x2 = x;
    this->y2 = y;
}
//---------------------------------------------------------------------------
// useful utility functions
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::SetupMotionVars(void) {
  float bounds[6];
  this->CurrentRenderer->ComputeVisiblePropBounds( bounds );
  if ( bounds[0] == VTK_LARGE_FLOAT ) this->DiagonalLength = 1.0;
  else {
    this->DiagonalLength =
    sqrt( (bounds[0] - bounds[1]) * (bounds[0] - bounds[1]) +
	      (bounds[2] - bounds[3]) * (bounds[2] - bounds[3]) +
	      (bounds[4] - bounds[5]) * (bounds[4] - bounds[5]) );
  }
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::MotionAlongVector(double vector[3], double amount) {
    double oldcampos[3], oldcamfoc[3];
    //
    this->CurrentCamera->GetPosition(oldcampos);
    this->CurrentCamera->GetFocalPoint(oldcamfoc);
    // move camera and focus along viewplanenormal
    this->CurrentCamera->SetPosition(
            oldcampos[0] - amount * vector[0],
            oldcampos[1] - amount * vector[1],
            oldcampos[2] - amount * vector[2]);
    this->CurrentCamera->SetFocalPoint(
            oldcamfoc[0] - amount * vector[0],
            oldcamfoc[1] - amount * vector[1],
            oldcamfoc[2] - amount * vector[2]);
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::ComputeLRVector(double vector[3]) {
  double viewplanenormal[3], viewup[3];
  this->CurrentCamera->GetViewPlaneNormal(viewplanenormal);
  this->CurrentCamera->GetViewUp(viewup);
  // Left Right axis
  vector[0] = (viewplanenormal[1] * viewup[2] -
               viewplanenormal[2] * viewup[1]);
  vector[1] = (viewplanenormal[2] * viewup[0] -
	           viewplanenormal[0] * viewup[2]);
  vector[2] = (viewplanenormal[0] * viewup[1] -
	           viewplanenormal[1] * viewup[0]);
}
//---------------------------------------------------------------------------
// Perform the motion
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::FlyByMouse(void) {
    double a_vector[3];
    double speed  = this->DiagonalLength * this->MotionStepSize * this->MotionUserScale;
    speed = speed * ( this->ShiftKey ? this->MotionAccelerationFactor : 1.0);
    // Sidestep (convert steering angles to left right movement
    // only because I added this after doing the angles earlier
    if (this->CtrlKey) {
        if (this->YawAngle!=0.0) {
            ComputeLRVector(a_vector);
    		MotionAlongVector(a_vector,-YawAngle*speed/4.0);
        }
        if (this->PitchAngle!=0.0) {
            this->CurrentCamera->GetViewUp(a_vector);
    		MotionAlongVector(a_vector,-PitchAngle*speed/4.0);
        }
    } else {
        this->CurrentCamera->Yaw(this->YawAngle);
        this->CurrentCamera->Pitch(this->PitchAngle);
    }
    this->OldX = x2;
    this->OldY = y2;
    this->YawAngle   = 0;
    this->PitchAngle = 0;
    //
    if (!this->CtrlKey) {
        this->CurrentCamera->GetViewPlaneNormal(a_vector);
        if (this->Flying)    MotionAlongVector(a_vector, speed);
        if (this->Reversing) MotionAlongVector(a_vector,-speed);
    }
}
//---------------------------------------------------------------------------
// Perform the motion
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::FlyByKey(void) {

    double speed  = this->DiagonalLength * this->MotionStepSize * this->MotionUserScale;
    speed = speed * ( this->ShiftKey ? this->MotionAccelerationFactor : 1.0);

	double aspeed = AngleStepSize* (this->ShiftKey ? AngleAccelerationFactor : 1.0);
    double a_vector[3];
    // Left and right
	if (this->CtrlKey) { // Sidestep
        ComputeLRVector(a_vector);
		if (KeysDown & 1) MotionAlongVector(a_vector,-speed);
		if (KeysDown & 2) MotionAlongVector(a_vector, speed);
	} else {
		if (KeysDown & 1) this->CurrentCamera->Yaw( aspeed);
		if (KeysDown & 2) this->CurrentCamera->Yaw(-aspeed);
	}

	// Up and Down
	if (this->CtrlKey) { // Sidestep
        this->CurrentCamera->GetViewUp(a_vector);
		if (KeysDown & 4) MotionAlongVector(a_vector,-speed);
		if (KeysDown & 8) MotionAlongVector(a_vector, speed);
	} else {
		if (KeysDown & 4) this->CurrentCamera->Pitch(-aspeed);
		if (KeysDown & 8) this->CurrentCamera->Pitch( aspeed);
	}

    // forward and backward
    this->CurrentCamera->GetViewPlaneNormal(a_vector);
    if (KeysDown & 16) MotionAlongVector(a_vector, speed);
    if (KeysDown & 32) MotionAlongVector(a_vector,-speed);
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::PrintSelf(ostream& os, vtkIndent indent) {
  vtkInteractorStyle::PrintSelf(os,indent);
  os << indent << "MotionStepSize: "
     << this->MotionStepSize << "\n";
  os << indent << "MotionAccelerationFactor: "
     << this->MotionAccelerationFactor << "\n";
  os << indent << "AngleStepSize: "
     << this->AngleStepSize << "\n";
  os << indent << "AngleAccelerationFactor: "
     << this->AngleAccelerationFactor << "\n";
  os << indent << "MotionUserScale: "
     << this->MotionUserScale << "\n";
}

<commit_msg>fixed compiler error<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkInteractorStyleFlight.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to John Biddiscombe of the Rutherford Appleton Laboratory
             who developed class.

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

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 REGENTS 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 "vtkInteractorStyleFlight.h"
#include "vtkMath.h"
#include "vtkCellPicker.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkObjectFactory.h"

//------------------------------------------------------------------------------
vtkInteractorStyleFlight* vtkInteractorStyleFlight::New()
{
  // irst try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkInteractorStyleFlight");
  if(ret)
    {
    return (vtkInteractorStyleFlight*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkInteractorStyleFlight;
}
//---------------------------------------------------------------------------
vtkInteractorStyleFlight::vtkInteractorStyleFlight()
{
  this->KeysDown     = 0;
  this->Flying       = 0;
  this->Reversing    = 0;
  this->TimerRunning = 0;
  this->DiagonalLength           = 1.0;
  this->MotionStepSize           = 1.0/250.0;
  this->MotionUserScale          = 1.0;  // +/- key adjustment
  this->MotionAccelerationFactor = 10.0;
  this->AngleStepSize            = 1.0;
  this->AngleAccelerationFactor  = 5.0;
  this->OldX = 0.0;
  this->OldY = 0.0;
}
//---------------------------------------------------------------------------
vtkInteractorStyleFlight::~vtkInteractorStyleFlight() {

}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::DoTimerStart(void) {
  if (this->TimerRunning) return;
  vtkRenderWindowInteractor *rwi = this->Interactor;
  rwi->CreateTimer(VTKI_TIMER_FIRST);
  this->TimerRunning = 1;
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::DoTimerStop(void) {
  if (!this->TimerRunning) return;
  vtkRenderWindowInteractor *rwi = this->Interactor;
  rwi->DestroyTimer();
  this->TimerRunning = 0;
}
//---------------------------------------------------------------------------
// Mouse event handlers
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnLeftButtonDown(int ctrl, int shift, int X, int Y) {
  this->UpdateInternalState(ctrl, shift, X, Y);
  if (!this->Reversing) {
      this->OldX        = this->x2 = X;
      this->OldY        = this->y2 = Y;
      this->YawAngle   = 0;
      this->PitchAngle = 0;
      this->DoTimerStart();
  }
  this->Flying       = 1;
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnLeftButtonUp(int ctrl, int shift, int X, int Y) {
  this->UpdateInternalState(ctrl, shift, X, Y);
  this->Flying       =  0;
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnRightButtonDown(int ctrl, int shift, int X, int Y) {
  this->UpdateInternalState(ctrl, shift, X, Y);
  if (!this->Flying) {
      this->OldX        = this->x2 = X;
      this->OldY        = this->y2 = Y;
      this->YawAngle   = 0;
      this->PitchAngle = 0;
      this->DoTimerStart();
  }
  this->Reversing    = 1;
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnRightButtonUp(int ctrl, int shift, int X, int Y) {
  this->UpdateInternalState(ctrl, shift, X, Y);
  this->Reversing    =  0;
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnMiddleButtonDown(int ctrl, int shift, int X, int Y) {
  this->UpdateInternalState(ctrl, shift, X, Y);
  // want to add some more functions???
  // I've got no middle mouse button :(
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnMiddleButtonUp(int ctrl, int shift, int X, int Y) {
  this->UpdateInternalState(ctrl, shift, X, Y);
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnMouseMove(int ctrl, int shift, int X, int Y) {
  this->UpdateInternalState(ctrl, shift, X, Y);
  if (Flying || Reversing) UpdateMouseSteering(X, Y);
}
//---------------------------------------------------------------------------
// Keyboard event handlers
// Note, OnChar is a key press down and then up event
// Note, OnKeyDown/OnKeyUp are more sensitive for controlling motion
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnChar(int ctrl, int shift,
                                char keycode, int vtkNotUsed(repeatcount))
{
  this->CtrlKey  = ctrl;
  this->ShiftKey = shift;
  switch (keycode)
    {
    // we are not overriding these keycodes
    case 'Q' :    case 'q' :
    case 'e' :    case 'E' :
    case 'u' :    case 'U' :
    case 'r' :    case 'R' :
    case 'w' :    case 'W' :
    case 's' :    case 'S' :
    case '3' :
    case 'p' :    case 'P' :
        vtkInteractorStyle::OnChar(ctrl, shift, keycode, 0);
        break;
    case '+' :
        this->MotionUserScale *= 2.0;
        break;
    case '-' :
        this->MotionUserScale *= 0.5;
        break;
    }
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnKeyDown(int ctrl, int shift,
                                char keycode, int vtkNotUsed(repeatcount))
{
  this->CtrlKey  = ctrl;
  this->ShiftKey = shift;
  // New light mode behaviour
  // Note that we'll need #defines for ARROW key defs under non win32 OS
#ifdef _WIN32
  switch (keycode)
    {
    case VK_LEFT  	: this->KeysDown |=1;  break;
    case VK_RIGHT 	: this->KeysDown |=2;  break;
    case VK_UP    	: this->KeysDown |=4;  break;
    case VK_DOWN  	: this->KeysDown |=8;  break;
    case 'a':
    case 'A'	: this->KeysDown |=16; break;
    case 'z':
    case 'Z' 	: this->KeysDown |=32; break;
    }
  // it may already be started but it doesn't matter
	if (KeysDown) this->DoTimerStart();
#endif
}

//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnKeyUp(int ctrl, int shift,
                                char keycode, int vtkNotUsed(repeatcount))
{
  this->CtrlKey  = ctrl;
  this->ShiftKey = shift;
#ifdef _WIN32
  switch (keycode)
    {
    case VK_LEFT  	: this->KeysDown &= ~1;  break;
    case VK_RIGHT 	: this->KeysDown &= ~2;  break;
    case VK_UP    	: this->KeysDown &= ~4;  break;
    case VK_DOWN  	: this->KeysDown &= ~8;  break;
    case 'a':
    case 'A'	: this->KeysDown &= ~16; break;
    case 'z':
    case 'Z' 	: this->KeysDown &= ~32; break;
    }
#endif
}
//---------------------------------------------------------------------------
// All actual motion is performed in the timer
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::OnTimer(void) {
    vtkRenderWindowInteractor *rwi = this->Interactor;
    // if we get a timer message we weren't expecting, just shut it down
	if (!Flying && !Reversing && !KeysDown) this->DoTimerStop();
	else {
        // Make sure CurrentCamera variable is initialized
        this->FindPokedCamera(this->OldX, this->OldY);
        this->SetupMotionVars();
        // Are we moving
        if (Flying || Reversing) FlyByMouse();
		if (KeysDown)            FlyByKey();
        // Tidy up Camera stuff
        this->CurrentCamera->OrthogonalizeViewUp();
        this->CurrentRenderer->ResetCameraClippingRange();
        // Make sure light follows camera if desired
        if (rwi->GetLightFollowCamera()) {
            this->CurrentLight->SetPosition(this->CurrentCamera->GetPosition());
            this->CurrentLight->SetFocalPoint(this->CurrentCamera->GetFocalPoint());
        }
        rwi->Render();
        rwi->CreateTimer(VTKI_TIMER_UPDATE);
	}
}
//---------------------------------------------------------------------------
// Calculate angles for next redraw in timer event
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::UpdateMouseSteering(int x, int y) {
	//
    double aspeed = this->AngleStepSize*(this->ShiftKey ? this->AngleAccelerationFactor : 1.0);
    //
    // we want to steer by an amount proportional to window viewangle and size
    vtkRenderWindowInteractor *rwi = this->Interactor;
    int *size = rwi->GetSize();
    double scalefactor = 5.0*this->CurrentCamera->GetViewAngle()/(double)size[0];
    double dx = - (x - this->OldX)*scalefactor;
    double dy =   (y - this->OldY)*scalefactor;
    this->YawAngle   = dx*aspeed;
    this->PitchAngle = dy*aspeed;
    this->x2 = x;
    this->y2 = y;
}
//---------------------------------------------------------------------------
// useful utility functions
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::SetupMotionVars(void) {
  float bounds[6];
  this->CurrentRenderer->ComputeVisiblePropBounds( bounds );
  if ( bounds[0] == VTK_LARGE_FLOAT ) this->DiagonalLength = 1.0;
  else {
    this->DiagonalLength =
    sqrt( (bounds[0] - bounds[1]) * (bounds[0] - bounds[1]) +
	      (bounds[2] - bounds[3]) * (bounds[2] - bounds[3]) +
	      (bounds[4] - bounds[5]) * (bounds[4] - bounds[5]) );
  }
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::MotionAlongVector(double vector[3], double amount) {
    double oldcampos[3], oldcamfoc[3];
    //
    this->CurrentCamera->GetPosition(oldcampos);
    this->CurrentCamera->GetFocalPoint(oldcamfoc);
    // move camera and focus along viewplanenormal
    this->CurrentCamera->SetPosition(
            oldcampos[0] - amount * vector[0],
            oldcampos[1] - amount * vector[1],
            oldcampos[2] - amount * vector[2]);
    this->CurrentCamera->SetFocalPoint(
            oldcamfoc[0] - amount * vector[0],
            oldcamfoc[1] - amount * vector[1],
            oldcamfoc[2] - amount * vector[2]);
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::ComputeLRVector(double vector[3]) {
  double viewplanenormal[3], viewup[3];
  this->CurrentCamera->GetViewPlaneNormal(viewplanenormal);
  this->CurrentCamera->GetViewUp(viewup);
  // Left Right axis
  vector[0] = (viewplanenormal[1] * viewup[2] -
               viewplanenormal[2] * viewup[1]);
  vector[1] = (viewplanenormal[2] * viewup[0] -
	           viewplanenormal[0] * viewup[2]);
  vector[2] = (viewplanenormal[0] * viewup[1] -
	           viewplanenormal[1] * viewup[0]);
}
//---------------------------------------------------------------------------
// Perform the motion
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::FlyByMouse(void) {
    double a_vector[3];
    double speed  = this->DiagonalLength * this->MotionStepSize * this->MotionUserScale;
    speed = speed * ( this->ShiftKey ? this->MotionAccelerationFactor : 1.0);
    // Sidestep (convert steering angles to left right movement
    // only because I added this after doing the angles earlier
    if (this->CtrlKey) {
        if (this->YawAngle!=0.0) {
            ComputeLRVector(a_vector);
    		MotionAlongVector(a_vector,-YawAngle*speed/4.0);
        }
        if (this->PitchAngle!=0.0) {
            this->CurrentCamera->GetViewUp(a_vector);
    		MotionAlongVector(a_vector,-PitchAngle*speed/4.0);
        }
    } else {
        this->CurrentCamera->Yaw(this->YawAngle);
        this->CurrentCamera->Pitch(this->PitchAngle);
    }
    this->OldX = x2;
    this->OldY = y2;
    this->YawAngle   = 0;
    this->PitchAngle = 0;
    //
    if (!this->CtrlKey) {
        this->CurrentCamera->GetViewPlaneNormal(a_vector);
        if (this->Flying)    MotionAlongVector(a_vector, speed);
        if (this->Reversing) MotionAlongVector(a_vector,-speed);
    }
}
//---------------------------------------------------------------------------
// Perform the motion
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::FlyByKey(void) {

    double speed  = this->DiagonalLength * this->MotionStepSize * this->MotionUserScale;
    speed = speed * ( this->ShiftKey ? this->MotionAccelerationFactor : 1.0);

	double aspeed = AngleStepSize* (this->ShiftKey ? AngleAccelerationFactor : 1.0);
    double a_vector[3];
    // Left and right
	if (this->CtrlKey) { // Sidestep
        ComputeLRVector(a_vector);
		if (KeysDown & 1) MotionAlongVector(a_vector,-speed);
		if (KeysDown & 2) MotionAlongVector(a_vector, speed);
	} else {
		if (KeysDown & 1) this->CurrentCamera->Yaw( aspeed);
		if (KeysDown & 2) this->CurrentCamera->Yaw(-aspeed);
	}

	// Up and Down
	if (this->CtrlKey) { // Sidestep
        this->CurrentCamera->GetViewUp(a_vector);
		if (KeysDown & 4) MotionAlongVector(a_vector,-speed);
		if (KeysDown & 8) MotionAlongVector(a_vector, speed);
	} else {
		if (KeysDown & 4) this->CurrentCamera->Pitch(-aspeed);
		if (KeysDown & 8) this->CurrentCamera->Pitch( aspeed);
	}

    // forward and backward
    this->CurrentCamera->GetViewPlaneNormal(a_vector);
    if (KeysDown & 16) MotionAlongVector(a_vector, speed);
    if (KeysDown & 32) MotionAlongVector(a_vector,-speed);
}
//---------------------------------------------------------------------------
void vtkInteractorStyleFlight::PrintSelf(ostream& os, vtkIndent indent) {
  vtkInteractorStyle::PrintSelf(os,indent);
  os << indent << "MotionStepSize: "
     << this->MotionStepSize << "\n";
  os << indent << "MotionAccelerationFactor: "
     << this->MotionAccelerationFactor << "\n";
  os << indent << "AngleStepSize: "
     << this->AngleStepSize << "\n";
  os << indent << "AngleAccelerationFactor: "
     << this->AngleAccelerationFactor << "\n";
  os << indent << "MotionUserScale: "
     << this->MotionUserScale << "\n";
}

<|endoftext|>


<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#ifndef __RAPICORN_THEME_HH__
#define __RAPICORN_THEME_HH__

#include <ui/primitives.hh>

namespace Rapicorn {

// == Decls ==
class StyleIface;
typedef std::shared_ptr<StyleIface> StyleIfaceP;

// == Config ==
class Config {
public:
  static String get (const String &setting, const String &fallback = "");
};

// == StyleColor ==
enum class StyleColor {
  NONE,
  FOREGROUND,
  BACKGROUND,
  DARK,
  DARK_SHADOW,
  DARK_GLINT,
  LIGHT,
  LIGHT_SHADOW,
  LIGHT_GLINT,
  FOCUS_FG,
  FOCUS_BG
};

// == StyleIface ==
class StyleIface : public std::enable_shared_from_this<StyleIface> {
public:
  Color foreground      (WidgetState state) { return state_color (state, StyleColor::FOREGROUND); }
  Color background      (WidgetState state) { return state_color (state, StyleColor::BACKGROUND); }
  Color dark_color      (WidgetState state) { return state_color (state, StyleColor::DARK); }
  Color dark_shadow     (WidgetState state) { return state_color (state, StyleColor::DARK_SHADOW); }
  Color dark_glint      (WidgetState state) { return state_color (state, StyleColor::DARK_GLINT); }
  Color light_color     (WidgetState state) { return state_color (state, StyleColor::LIGHT); }
  Color light_shadow    (WidgetState state) { return state_color (state, StyleColor::LIGHT_SHADOW); }
  Color light_glint     (WidgetState state) { return state_color (state, StyleColor::LIGHT_GLINT); }
  Color focus_color     (WidgetState state) { return state_color (state, StyleColor::FOCUS_FG); }
  virtual Color      theme_color        (double hue360, double saturation100, double brightness100, const String &detail = "") = 0;
  virtual Color      state_color        (WidgetState state, StyleColor color_type, const String &detail = "") = 0;
  static StyleIfaceP load               (const String &theme_file);
  static StyleIfaceP fallback           ();
  static WidgetState state_from_name    (const String &lower_case_state_name);
  static uint64      state_from_list    (const String &state_list);
  static String      pick_fragment      (const String &fragment, WidgetState state, const StringVector &fragment_list);
};

} // Rapicorn

#endif  /* __RAPICORN_THEME_HH__ */
<commit_msg>UI: style: remove unused methods<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#ifndef __RAPICORN_THEME_HH__
#define __RAPICORN_THEME_HH__

#include <ui/primitives.hh>

namespace Rapicorn {

// == Decls ==
class StyleIface;
typedef std::shared_ptr<StyleIface> StyleIfaceP;

// == Config ==
class Config {
public:
  static String get (const String &setting, const String &fallback = "");
};

// == StyleColor ==
enum class StyleColor {
  NONE,
  FOREGROUND,
  BACKGROUND,
  DARK,
  DARK_SHADOW,
  DARK_GLINT,
  LIGHT,
  LIGHT_SHADOW,
  LIGHT_GLINT,
  FOCUS_FG,
  FOCUS_BG
};

// == StyleIface ==
class StyleIface : public std::enable_shared_from_this<StyleIface> {
public:
  virtual Color      theme_color        (double hue360, double saturation100, double brightness100, const String &detail = "") = 0;
  virtual Color      state_color        (WidgetState state, StyleColor color_type, const String &detail = "") = 0;
  static StyleIfaceP load               (const String &theme_file);
  static StyleIfaceP fallback           ();
  static WidgetState state_from_name    (const String &lower_case_state_name);
  static uint64      state_from_list    (const String &state_list);
  static String      pick_fragment      (const String &fragment, WidgetState state, const StringVector &fragment_list);
};

} // Rapicorn

#endif  /* __RAPICORN_THEME_HH__ */
<|endoftext|>


<commit_before>// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule
//
// 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 "src/ext/x64asm/include/x64asm.h"
#include "src/state/cpu_state.h"

using namespace cpputil;
using namespace std;
using namespace x64asm;

namespace stoke {

ostream& CpuState::write_text(ostream& os) const {
  const char* gps[] = {
    "%rax", "%rcx", "%rdx", "%rbx", "%rsp", "%rbp", "%rsi", "%rdi",
    "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15"
  };

	// SSE register names will vary depending on target
  const char* sses[] = {
#ifdef __AVX__
    "%ymm0", "%ymm1", "%ymm2", "%ymm3", "%ymm4", "%ymm5", "%ymm6", "%ymm7",
    "%ymm8", "%ymm9", "%ymm10", "%ymm11", "%ymm12", "%ymm13", "%ymm14", "%ymm15"
#else
    "%xmm0", "%xmm1", "%xmm2", "%xmm3", "%xmm4", "%xmm5", "%xmm6", "%xmm7",
    "%xmm8", "%xmm9", "%xmm10", "%xmm11", "%xmm12", "%xmm13", "%xmm14", "%xmm15"
#endif
  };

  const char* rflags[] = {
    "%cf", "%1", "%pf", "%0", "%af", "%0", "%zf", "%sf", "%tf", "%if",
    "%df", "%of", "%iopl[0]", "%iopl[1]", "%nt", "%0", "%rf", "%vm", "%ac", "%vif",
    "%vip", "%id"
  };

  gp.write_text(os, gps, 5);
  os << endl;
  os << endl;

  sse.write_text(os, sses, 3);
  os << endl;
  os << endl;

  rf.write_text(os, rflags, 1);
  os << endl;
  os << endl;

  stack.write_text(os);
  os << endl;
  os << endl;

  heap.write_text(os);

  return os;
}

istream& CpuState::read_text(istream& is) {
  string ignore;

  code = ErrorCode::NORMAL;

  gp.read_text(is);
  getline(is, ignore);
  getline(is, ignore);

  sse.read_text(is);
  getline(is, ignore);
  getline(is, ignore);

  rf.read_text(is);
  getline(is, ignore);
  getline(is, ignore);

  stack.read_text(is);
  getline(is, ignore);
  getline(is, ignore);

  heap.read_text(is);

  // Stack addresses should be strictly greater than heap addresses
  if (stack.lower_bound() <= heap.upper_bound()) {
    is.setstate(ios::failbit);
  }

  return is;
}

void CpuState::convert_from_model(SMTSolver& smt, string& name_suffix) {

  for(size_t i = 0; i < r64s.size(); ++i) {
    stringstream name;
    name << r64s[i] << name_suffix;
    gp[r64s[i]] = smt.get_model_bv(name.str(), 1);
  }

	#ifdef __AVX__
		constexpr size_t width = 4;
	#else
		constexpr size_t width = 2;
	#endif
  for(size_t i = 0; i < ymms.size(); ++i) {
    stringstream name;
    name << ymms[i] << name_suffix;
    sse[ymms[i]] = smt.get_model_bv(name.str(), 2);
  }
  for(size_t i = 0; i < eflags.size(); ++i) {
    if(!rf.is_status(eflags[i].index()))
      continue;

    stringstream name;
    name << eflags[i] << name_suffix;
    rf.set(eflags[i].index(), smt.get_model_bool(name.str()));
  }

}

} // namespace stoke

<commit_msg>Astyle maybe?<commit_after>// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule
//
// 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 "src/ext/x64asm/include/x64asm.h"
#include "src/state/cpu_state.h"

using namespace cpputil;
using namespace std;
using namespace x64asm;

namespace stoke {

ostream& CpuState::write_text(ostream& os) const {
  const char* gps[] = {
    "%rax", "%rcx", "%rdx", "%rbx", "%rsp", "%rbp", "%rsi", "%rdi",
    "%r8", "%r9", "%r10", "%r11", "%r12", "%r13", "%r14", "%r15"
  };

  // SSE register names will vary depending on target
  const char* sses[] = {
#ifdef __AVX__
    "%ymm0", "%ymm1", "%ymm2", "%ymm3", "%ymm4", "%ymm5", "%ymm6", "%ymm7",
    "%ymm8", "%ymm9", "%ymm10", "%ymm11", "%ymm12", "%ymm13", "%ymm14", "%ymm15"
#else
    "%xmm0", "%xmm1", "%xmm2", "%xmm3", "%xmm4", "%xmm5", "%xmm6", "%xmm7",
    "%xmm8", "%xmm9", "%xmm10", "%xmm11", "%xmm12", "%xmm13", "%xmm14", "%xmm15"
#endif
  };

  const char* rflags[] = {
    "%cf", "%1", "%pf", "%0", "%af", "%0", "%zf", "%sf", "%tf", "%if",
    "%df", "%of", "%iopl[0]", "%iopl[1]", "%nt", "%0", "%rf", "%vm", "%ac", "%vif",
    "%vip", "%id"
  };

  gp.write_text(os, gps, 5);
  os << endl;
  os << endl;

  sse.write_text(os, sses, 3);
  os << endl;
  os << endl;

  rf.write_text(os, rflags, 1);
  os << endl;
  os << endl;

  stack.write_text(os);
  os << endl;
  os << endl;

  heap.write_text(os);

  return os;
}

istream& CpuState::read_text(istream& is) {
  string ignore;

  code = ErrorCode::NORMAL;

  gp.read_text(is);
  getline(is, ignore);
  getline(is, ignore);

  sse.read_text(is);
  getline(is, ignore);
  getline(is, ignore);

  rf.read_text(is);
  getline(is, ignore);
  getline(is, ignore);

  stack.read_text(is);
  getline(is, ignore);
  getline(is, ignore);

  heap.read_text(is);

  // Stack addresses should be strictly greater than heap addresses
  if (stack.lower_bound() <= heap.upper_bound()) {
    is.setstate(ios::failbit);
  }

  return is;
}

void CpuState::convert_from_model(SMTSolver& smt, string& name_suffix) {

  for(size_t i = 0; i < r64s.size(); ++i) {
    stringstream name;
    name << r64s[i] << name_suffix;
    gp[r64s[i]] = smt.get_model_bv(name.str(), 1);
  }

#ifdef __AVX__
  constexpr size_t width = 4;
#else
  constexpr size_t width = 2;
#endif
  for(size_t i = 0; i < ymms.size(); ++i) {
    stringstream name;
    name << ymms[i] << name_suffix;
    sse[ymms[i]] = smt.get_model_bv(name.str(), 2);
  }
  for(size_t i = 0; i < eflags.size(); ++i) {
    if(!rf.is_status(eflags[i].index()))
      continue;

    stringstream name;
    name << eflags[i] << name_suffix;
    rf.set(eflags[i].index(), smt.get_model_bool(name.str()));
  }

}

} // namespace stoke

<|endoftext|>


<commit_before> //
 // This file is part of Easylogging++ samples
 // PerformanceTrackingCallback sample to customize performance output
 //
 // Revision 1.0
 // @author mkhan3189
 //

#include "easylogging++.h"

_INITIALIZE_EASYLOGGINGPP

class MyPerformanceTrackingOutput : public el::PerformanceTrackingCallback {
public:
    MyPerformanceTrackingOutput() {
        el::PerformanceTrackingCallback* defaultCallback = el::Helpers::performanceTrackingCallback<el::base::DefaultPerformanceTrackingCallback>("DefaultPerformanceTrackingCallback");
//        defaultCallback->setEnabled(false);
    }
    virtual ~MyPerformanceTrackingOutput() {
        el::PerformanceTrackingCallback* defaultCallback = el::Helpers::performanceTrackingCallback<el::base::DefaultPerformanceTrackingCallback>("DefaultPerformanceTrackingCallback");
        defaultCallback->setEnabled(true);
    }
protected:
    void handle(const el::PerformanceTrackingData* data) {
        if (data->firstCheckpoint()) { return; } // ignore first check point
        el::base::type::stringstream_t ss;
        ss << data->blockName()->c_str() << " took " <<  *data->formattedTimeTaken() << " to run";
        if (data->dataType() == el::PerformanceTrackingData::DataType::Checkpoint) {
            ss << " [CHECKPOINT ONLY] ";
        }
        CLOG(INFO, data->loggerId().c_str()) << ss.str();
    }
};

int main(void) {

    TIMED_SCOPE(mainBlock, "main");

    el::Helpers::installPerformanceTrackingCallback<MyPerformanceTrackingOutput>("MyPerformanceTrackingOutput");

    {
        TIMED_SCOPE(timer, "myblock");
        for (int i = 0; i <= 500; ++i) {
            // Spend time
            for (int j = 0; j < 10000; ++j) { std::string tmp; }
            if (i % 100 == 0) {
                timer.checkpoint(std::string(std::string("checkpoint at ") + std::to_string(static_cast<unsigned long long>(i))).c_str());
            }
        }
    }
    LOG(INFO) << "By now, you should get performance result of above scope";
    el::Helpers::uninstallPerformanceTrackingCallback<MyPerformanceTrackingOutput>("MyPerformanceTrackingOutput");
    // You will get "main" block in normal format (default)
    return 0;
}
<commit_msg>updated sample<commit_after> //
 // This file is part of Easylogging++ samples
 // PerformanceTrackingCallback sample to customize performance output
 //
 // Revision 1.0
 // @author mkhan3189
 //

#include "easylogging++.h"

_INITIALIZE_EASYLOGGINGPP

class MyPerformanceTrackingOutput : public el::PerformanceTrackingCallback {
public:
    MyPerformanceTrackingOutput() {
        el::PerformanceTrackingCallback* defaultCallback =
            el::Helpers::performanceTrackingCallback<el::base::DefaultPerformanceTrackingCallback>("DefaultPerformanceTrackingCallback");
        defaultCallback->setEnabled(false);
    }
    virtual ~MyPerformanceTrackingOutput() {
        el::PerformanceTrackingCallback* defaultCallback =
            el::Helpers::performanceTrackingCallback<el::base::DefaultPerformanceTrackingCallback>("DefaultPerformanceTrackingCallback");
        defaultCallback->setEnabled(true);
    }
protected:
    void handle(const el::PerformanceTrackingData* data) {
        if (data->firstCheckpoint()) { return; } // ignore first check point
        el::base::type::stringstream_t ss;
        ss << data->blockName()->c_str() << " took " <<  *data->formattedTimeTaken() << " to run";
        if (data->dataType() == el::PerformanceTrackingData::DataType::Checkpoint) {
            ss << " [CHECKPOINT ONLY] ";
        }
        CLOG(INFO, data->loggerId().c_str()) << ss.str();
    }
};

int main(void) {

    TIMED_SCOPE(mainBlock, "main");

    el::Helpers::installPerformanceTrackingCallback<MyPerformanceTrackingOutput>("MyPerformanceTrackingOutput");

    {
        TIMED_SCOPE(timer, "myblock");
        for (int i = 0; i <= 500; ++i) {
            // Spend time
            for (int j = 0; j < 10000; ++j) { std::string tmp; }
            if (i % 100 == 0) {
                timer.checkpoint(std::string(std::string("checkpoint at ") + std::to_string(static_cast<unsigned long long>(i))).c_str());
            }
        }
    }
    LOG(INFO) << "By now, you should get performance result of above scope";
    el::Helpers::uninstallPerformanceTrackingCallback<MyPerformanceTrackingOutput>("MyPerformanceTrackingOutput");
    // You will get "main" block in normal format (default)
    return 0;
}
<|endoftext|>


<commit_before>/****************************************************************************

 This file is part of the GLC-lib library.
 Copyright (C) 2005 Laurent Ribon (laumaya@users.sourceforge.net)
 Version 0.9, packaged on Novemeber, 2005.

 http://glc-lib.sourceforge.net

 GLC-lib is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 GLC-lib 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 GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*****************************************************************************/

//! \file glc_collection.cpp implementation of the GLC_Collection class.

#include <QtDebug>

#include "glc_collection.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

GLC_Collection::GLC_Collection()
: m_ListeID(0)
, m_bListeIsValid(false)
{
}

GLC_Collection::~GLC_Collection()
{
	Erase();
}
//////////////////////////////////////////////////////////////////////
// Fonctions Set
//////////////////////////////////////////////////////////////////////
// Ajoute une gomtrie  la collection
bool GLC_Collection::AddGLC_Geom(GLC_Geometry* pGeom)
{
	CGeomMap::iterator iGeom= m_TheMap.find(pGeom->GetID());

	if (iGeom == m_TheMap.end())
	{	// Ok, la cl n'est pas prise
		// Ajoute la gomtrie
		m_TheMap[pGeom->GetID()]= pGeom;
		// Ajoute la sous liste
		m_ListeMap[pGeom->GetID()] = 0;
		//TRACE("GLC_Collection::AddGLC_Geom : Element Ajout avec succs\n");

		// Validit de la liste
		m_bListeIsValid= false;
		return true;

	}
	else
	{	// KO, la cl est prise
		qDebug("GLC_Collection::AddGLC_Geom : Element already in collection");
		return false;
	}

}

// Supprime une gomtrie de la collection et la gomtrie
bool GLC_Collection::DelGLC_Geom(GLC_uint Key)
{

	CGeomMap::iterator iGeom= m_TheMap.find(Key);

	if (iGeom != m_TheMap.end())
	{	// Ok, la cl existe
		delete iGeom.value();		// Supprime la gomtrie
		m_TheMap.remove(Key);		// Supprime le conteneur
		// Recherche la liste
		CListeMap::iterator iListe= m_ListeMap.find(Key);
		// \todo Vrifier que la liste d'affichage est trouve
		if (!!iListe.value())
		{
			glDeleteLists(iListe.value(),1);
			//qDebug("GLC_Collection::DelGLC_Geom : Sous liste %u Supprime\n", RemListe);
		}
		m_ListeMap.remove(Key);		// Supprime le conteneur

		// Validit de la liste
		m_bListeIsValid= false;

		//qDebug("GLC_Collection::DelGLC_Geom : Element succesfuly deleted);
		return true;

	}
	else
	{	// KO, la cl n'existe pas
		qDebug("GLC_Collection::DelGLC_Geom : Elment non Supprim");
		return false;
	}

}

// Supprime une gomtrie de la collection
bool GLC_Collection::RemGLC_Geom(GLC_uint Key)
{
	CGeomMap::iterator iGeom= m_TheMap.find(Key);

	if (iGeom != m_TheMap.end())
	{	// Ok, la cl existe
		// On ne Supprime pas la gomtrie
		m_TheMap.remove(Key);		// Supprime le conteneur
		// Recherche la liste
		CListeMap::iterator iListe= m_ListeMap.find(Key);
		// TODO Vrifier que la liste d'affichage est trouve
		if (!!iListe.value())
		{
			glDeleteLists(iListe.value(),1);
			//qDebug("GLC_Collection::RemGLC_Geom : Sous liste %u Supprime", RemListe);
		}
		m_ListeMap.remove(Key);		// Supprime le conteneur

		// Validit de la liste
		m_bListeIsValid= false;

		//qDebug("GLC_Collection::RemGLC_Geom : Element Supprim avec succs");
		return true;

	}
	else
	{	// KO, la cl n'existe pas
		qDebug("GLC_Collection::RemGLC_Geom : Elment non Supprim");
		return false;
	}

}

// Vide la collection
void GLC_Collection::Erase(void)
{
	// Suppression des gomtries
	CGeomMap::iterator iEntry= m_TheMap.begin();

    while (iEntry != m_TheMap.constEnd())
    {
        // Supprime l'objet
        delete iEntry.value();
        ++iEntry;
    }
    // Vide la table de hachage principale
    m_TheMap.clear();

	// Fin de la Suppression des gomtries

	// Suppression des sous listes d'affichages
	CListeMap::iterator iListEntry= m_ListeMap.begin();

    while (iListEntry != m_ListeMap.constEnd())
    {
        // Supprime l'objet
        if (!!iListEntry.value()) glDeleteLists(iListEntry.value(), 1);
        ++iListEntry;
    }
    // Vide la table de hachage de liste
    m_ListeMap.clear();

	// Supprime la liste d'affichage
	DeleteListe();
	// Fin des Suppressions des sous listes d'affichages

}

// Retourne le pointeur d'un lment de la collection
GLC_Geometry* GLC_Collection::GetElement(GLC_uint Key)
{
	CGeomMap::iterator iGeom= m_TheMap.find(Key);

	if (iGeom != m_TheMap.end())
	{	// Ok, la cl est trouv
		return iGeom.value();
	}
	else
	{	// KO, la cl n'est pas trouv
		return NULL;
	}
}

//////////////////////////////////////////////////////////////////////
// Fonctions OpenGL
//////////////////////////////////////////////////////////////////////
void GLC_Collection::GlExecute(void)
{
	if (GetNumber() > 0)
	{
		CreateMemberList();		// Si ncessaire

		CreateSousList();		// Si ncessaire

		if (m_bListeIsValid)
		{	// La liste de la collection OK
			glCallList(m_ListeID);
		}
		else
		{
			if(MemberIsUpToDate())
			{
				CreationListe();
			}
			else
			{
				m_bListeIsValid= false;
				qDebug("GLC_Collection::DrawGl : CreatMemberList KO -> Affichage lments\n");
			}
		}

		// Gestion erreur OpenGL
		GLenum errCode;
		if ((errCode= glGetError()) != GL_NO_ERROR)
		{
			const GLubyte* errString;
			errString = gluErrorString(errCode);
			qDebug("GLC_Collection::DrawGl ERREUR OPENGL %s\n", errString);
		}
	}
}

// Affiche les lments de la collection
void GLC_Collection::GlDraw(void)
{
	CListeMap::iterator iEntry= m_ListeMap.begin();

    while (iEntry != m_ListeMap.constEnd())
    {
        glCallList(iEntry.value());
        ++iEntry;
    }

	// Gestion erreur OpenGL
	GLenum errCode;
	if ((errCode= glGetError()) != GL_NO_ERROR)
	{
		const GLubyte* errString;
		errString = gluErrorString(errCode);
		qDebug("GLC_Collection::GlDraw ERREUR OPENGL %s\n", errString);
	}

}

// Cration des listes d'affichages des membres
void GLC_Collection::CreateMemberList(void)
{
	CGeomMap::iterator iEntry= m_TheMap.begin();

    while (iEntry != m_TheMap.constEnd())
    {
    	if(!iEntry.value()->GetListIsValid())
    	{
    		iEntry.value()->CreateList(GL_COMPILE);
    	}
    	// Passe au Suivant
    	iEntry++;
    }

	// Gestion erreur OpenGL
	if (glGetError() != GL_NO_ERROR)
	{
		qDebug("GLC_Collection::CreateMemberList ERREUR OPENGL");
	}

}
// Cration des sous listes d'affichages
void GLC_Collection::CreateSousList(void)
{
	CGeomMap::iterator iEntry= m_TheMap.begin();
	CListeMap::iterator iListEntry;

	GLuint ListeID= 0;
    while (iEntry != m_TheMap.constEnd())
    {
    	if(!iEntry.value()->GetValidity())
    	{
    		iListEntry= m_ListeMap.find(iEntry.key());
    		if(iListEntry != m_ListeMap.constEnd())
    		{	// Numro non gnr
    			ListeID= glGenLists(1);
    			m_ListeMap[iEntry.key()]= ListeID;
    			m_bListeIsValid= false;
    		}
    		// Cration de la liste
    		glNewList(ListeID, GL_COMPILE);
    			iEntry.value()->GlExecute(GL_COMPILE);
    		glEndList();
    		//qDebug("GLC_Collection::CreateSousList : Liste d'affichage %u cr", ListeID);
     	}
    	// Passe au Suivant
    	iEntry++;
    }

	// Gestion erreur OpenGL
	if (glGetError() != GL_NO_ERROR)
	{
		qDebug("GLC_Collection::CreateSousList ERREUR OPENGL\n");
	}

}

//////////////////////////////////////////////////////////////////////
// Fonctions de services prives
//////////////////////////////////////////////////////////////////////
// Verifie si les listes d'affichage des membres sont  jour
bool GLC_Collection::MemberListIsUpToDate(void)
{
	CGeomMap::iterator iEntry= m_TheMap.begin();

    while (iEntry != m_TheMap.constEnd())
    {
    	if(iEntry.value()->GetListIsValid() || !iEntry.value()->GetIsVisible())
    	{	// Gomtrie valide ou non visible.
    		iEntry++;
    	}
    	else
    	{
 			//qDebug("GLC_Collection::MemberListIsUpToDate : Liste d'affichage d'un enfant non  jour");
			return false;
    	}
     }

	return true;	// Toutes les listes sont  jour

}

// Verifie si les membres sont  jour
bool GLC_Collection::MemberIsUpToDate(void)
{

	CGeomMap::iterator iEntry= m_TheMap.begin();

    while (iEntry != m_TheMap.constEnd())
    {
    	if(iEntry.value()->GetValidity() || !iEntry.value()->GetIsVisible())
    	{	// Membre valide ou non visible.
    		iEntry++;
    	}
    	else
    	{
 			//qDebug("GLC_Collection::MemberIsUpToDate : Prop Geom d'un enfant non  jour");
			return false;
    	}
     }

	return true;	// Toutes les Membres sont  jour

}

// Cration de la liste d'affichage de la collection
bool GLC_Collection::CreationListe(void)
{

	if(!m_ListeID)		// La liste n'a jamais t cr
	{
		m_ListeID= glGenLists(1);

		if (!m_ListeID)	// ID de liste non obtenu
		{
			GlDraw();
			//qDebug("GLC_Collection::CreateList : ERREUR Liste d'affichage NON cr");
			return false;	// Gomtrie affich mais pas de liste de cr
		}
	}

	// Cration de la liste
	glNewList(m_ListeID, GL_COMPILE_AND_EXECUTE);
		// Affichage des lments de la collection
		GlDraw();
	glEndList();

	// Validit de la liste
	m_bListeIsValid= true;

	//qDebug("GLC_Collection::CreateList : Liste d'affichage %u cr", m_ListID);

	// Gestion erreur OpenGL
	GLenum errCode;
	if ((errCode= glGetError()) != GL_NO_ERROR)
	{
		const GLubyte* errString;
		errString = gluErrorString(errCode);
		qDebug("GLC_Collection::CreationListe ERREUR OPENGL %s\n", errString);
	}

	return true;	// Gomtrie affich et liste cr

}
<commit_msg>Rename some members.<commit_after>/****************************************************************************

 This file is part of the GLC-lib library.
 Copyright (C) 2005 Laurent Ribon (laumaya@users.sourceforge.net)
 Version 0.9, packaged on Novemeber, 2005.

 http://glc-lib.sourceforge.net

 GLC-lib is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 GLC-lib 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 GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*****************************************************************************/

//! \file glc_collection.cpp implementation of the GLC_Collection class.

#include <QtDebug>

#include "glc_collection.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

GLC_Collection::GLC_Collection()
: m_ListID(0)
, m_ListIsValid(false)
{
}

GLC_Collection::~GLC_Collection()
{
	Erase();
}
//////////////////////////////////////////////////////////////////////
// Fonctions Set
//////////////////////////////////////////////////////////////////////
// Ajoute une gomtrie  la collection
bool GLC_Collection::AddGLC_Geom(GLC_Geometry* pGeom)
{
	CGeomMap::iterator iGeom= m_TheMap.find(pGeom->GetID());

	if (iGeom == m_TheMap.end())
	{	// Ok, la cl n'est pas prise
		// Ajoute la gomtrie
		m_TheMap[pGeom->GetID()]= pGeom;
		// Ajoute la sous liste
		m_ListMap[pGeom->GetID()] = 0;
		//TRACE("GLC_Collection::AddGLC_Geom : Element Ajout avec succs\n");

		// Validit de la liste
		m_ListIsValid= false;
		return true;

	}
	else
	{	// KO, la cl est prise
		qDebug("GLC_Collection::AddGLC_Geom : Element already in collection");
		return false;
	}

}

// Supprime une gomtrie de la collection et la gomtrie
bool GLC_Collection::DelGLC_Geom(GLC_uint Key)
{

	CGeomMap::iterator iGeom= m_TheMap.find(Key);

	if (iGeom != m_TheMap.end())
	{	// Ok, la cl existe
		delete iGeom.value();		// Supprime la gomtrie
		m_TheMap.remove(Key);		// Supprime le conteneur
		// Recherche la liste
		CListeMap::iterator iListe= m_ListMap.find(Key);
		// \todo Vrifier que la liste d'affichage est trouve
		if (!!iListe.value())
		{
			glDeleteLists(iListe.value(),1);
			//qDebug("GLC_Collection::DelGLC_Geom : Sous liste %u Supprime\n", RemListe);
		}
		m_ListMap.remove(Key);		// Supprime le conteneur

		// Validit de la liste
		m_ListIsValid= false;

		//qDebug("GLC_Collection::DelGLC_Geom : Element succesfuly deleted);
		return true;

	}
	else
	{	// KO, la cl n'existe pas
		qDebug("GLC_Collection::DelGLC_Geom : Elment non Supprim");
		return false;
	}

}

// Supprime une gomtrie de la collection
bool GLC_Collection::RemGLC_Geom(GLC_uint Key)
{
	CGeomMap::iterator iGeom= m_TheMap.find(Key);

	if (iGeom != m_TheMap.end())
	{	// Ok, la cl existe
		// On ne Supprime pas la gomtrie
		m_TheMap.remove(Key);		// Supprime le conteneur
		// Recherche la liste
		CListeMap::iterator iListe= m_ListMap.find(Key);
		// TODO Vrifier que la liste d'affichage est trouve
		if (!!iListe.value())
		{
			glDeleteLists(iListe.value(),1);
			//qDebug("GLC_Collection::RemGLC_Geom : Sous liste %u Supprime", RemListe);
		}
		m_ListMap.remove(Key);		// Supprime le conteneur

		// Validit de la liste
		m_ListIsValid= false;

		//qDebug("GLC_Collection::RemGLC_Geom : Element Supprim avec succs");
		return true;

	}
	else
	{	// KO, la cl n'existe pas
		qDebug("GLC_Collection::RemGLC_Geom : Elment non Supprim");
		return false;
	}

}

// Vide la collection
void GLC_Collection::Erase(void)
{
	// Suppression des gomtries
	CGeomMap::iterator iEntry= m_TheMap.begin();

    while (iEntry != m_TheMap.constEnd())
    {
        // Supprime l'objet
        delete iEntry.value();
        ++iEntry;
    }
    // Vide la table de hachage principale
    m_TheMap.clear();

	// Fin de la Suppression des gomtries

	// Suppression des sous listes d'affichages
	CListeMap::iterator iListEntry= m_ListMap.begin();

    while (iListEntry != m_ListMap.constEnd())
    {
        // Supprime l'objet
        if (!!iListEntry.value()) glDeleteLists(iListEntry.value(), 1);
        ++iListEntry;
    }
    // Vide la table de hachage de liste
    m_ListMap.clear();

	// Supprime la liste d'affichage
	DeleteList();
	// Fin des Suppressions des sous listes d'affichages

}

// Retourne le pointeur d'un lment de la collection
GLC_Geometry* GLC_Collection::GetElement(GLC_uint Key)
{
	CGeomMap::iterator iGeom= m_TheMap.find(Key);

	if (iGeom != m_TheMap.end())
	{	// Ok, la cl est trouv
		return iGeom.value();
	}
	else
	{	// KO, la cl n'est pas trouv
		return NULL;
	}
}

//////////////////////////////////////////////////////////////////////
// Fonctions OpenGL
//////////////////////////////////////////////////////////////////////
void GLC_Collection::GlExecute(void)
{
	if (GetNumber() > 0)
	{
		CreateMemberLists();		// Si ncessaire

		CreateSubLists();		// Si ncessaire

		if (m_ListIsValid)
		{	// La liste de la collection OK
			glCallList(m_ListID);
		}
		else
		{
			if(MemberIsUpToDate())
			{
				CreateList();
			}
			else
			{
				m_ListIsValid= false;
				qDebug("GLC_Collection::DrawGl : CreatMemberList KO -> Affichage lments\n");
			}
		}

		// Gestion erreur OpenGL
		GLenum errCode;
		if ((errCode= glGetError()) != GL_NO_ERROR)
		{
			const GLubyte* errString;
			errString = gluErrorString(errCode);
			qDebug("GLC_Collection::DrawGl ERREUR OPENGL %s\n", errString);
		}
	}
}

// Affiche les lments de la collection
void GLC_Collection::GlDraw(void)
{
	CListeMap::iterator iEntry= m_ListMap.begin();

    while (iEntry != m_ListMap.constEnd())
    {
        glCallList(iEntry.value());
        ++iEntry;
    }

	// Gestion erreur OpenGL
	GLenum errCode;
	if ((errCode= glGetError()) != GL_NO_ERROR)
	{
		const GLubyte* errString;
		errString = gluErrorString(errCode);
		qDebug("GLC_Collection::GlDraw ERREUR OPENGL %s\n", errString);
	}

}

// Cration des listes d'affichages des membres
void GLC_Collection::CreateMemberLists(void)
{
	CGeomMap::iterator iEntry= m_TheMap.begin();

    while (iEntry != m_TheMap.constEnd())
    {
    	if(!iEntry.value()->GetListIsValid())
    	{
    		iEntry.value()->CreateList(GL_COMPILE);
    	}
    	// Passe au Suivant
    	iEntry++;
    }

	// Gestion erreur OpenGL
	if (glGetError() != GL_NO_ERROR)
	{
		qDebug("GLC_Collection::CreateMemberList ERREUR OPENGL");
	}

}
// Cration des sous listes d'affichages
void GLC_Collection::CreateSubLists(void)
{
	CGeomMap::iterator iEntry= m_TheMap.begin();
	CListeMap::iterator iListEntry;

	GLuint ListeID= 0;
    while (iEntry != m_TheMap.constEnd())
    {
    	if(!iEntry.value()->GetValidity())
    	{
    		iListEntry= m_ListMap.find(iEntry.key());
    		if(iListEntry != m_ListMap.constEnd())
    		{	// Numro non gnr
    			ListeID= glGenLists(1);
    			m_ListMap[iEntry.key()]= ListeID;
    			m_ListIsValid= false;
    		}
    		// Cration de la liste
    		glNewList(ListeID, GL_COMPILE);
    			iEntry.value()->GlExecute(GL_COMPILE);
    		glEndList();
    		//qDebug("GLC_Collection::CreateSubLists : Liste d'affichage %u cr", ListeID);
     	}
    	// Passe au Suivant
    	iEntry++;
    }

	// Gestion erreur OpenGL
	if (glGetError() != GL_NO_ERROR)
	{
		qDebug("GLC_Collection::CreateSousList ERREUR OPENGL\n");
	}

}

//////////////////////////////////////////////////////////////////////
// Fonctions de services prives
//////////////////////////////////////////////////////////////////////
// Verifie si les listes d'affichage des membres sont  jour
bool GLC_Collection::MemberListIsUpToDate(void)
{
	CGeomMap::iterator iEntry= m_TheMap.begin();

    while (iEntry != m_TheMap.constEnd())
    {
    	if(iEntry.value()->GetListIsValid() || !iEntry.value()->GetIsVisible())
    	{	// Gomtrie valide ou non visible.
    		iEntry++;
    	}
    	else
    	{
 			//qDebug("GLC_Collection::MemberListIsUpToDate : Liste d'affichage d'un enfant non  jour");
			return false;
    	}
     }

	return true;	// Toutes les listes sont  jour

}

// Verifie si les membres sont  jour
bool GLC_Collection::MemberIsUpToDate(void)
{

	CGeomMap::iterator iEntry= m_TheMap.begin();

    while (iEntry != m_TheMap.constEnd())
    {
    	if(iEntry.value()->GetValidity() || !iEntry.value()->GetIsVisible())
    	{	// Membre valide ou non visible.
    		iEntry++;
    	}
    	else
    	{
 			//qDebug("GLC_Collection::MemberIsUpToDate : Prop Geom d'un enfant non  jour");
			return false;
    	}
     }

	return true;	// Toutes les Membres sont  jour

}

// Cration de la liste d'affichage de la collection
bool GLC_Collection::CreateList(void)
{

	if(!m_ListID)		// La liste n'a jamais t cr
	{
		m_ListID= glGenLists(1);

		if (!m_ListID)	// ID de liste non obtenu
		{
			GlDraw();
			//qDebug("GLC_Collection::CreateList : ERREUR Liste d'affichage NON cr");
			return false;	// Gomtrie affich mais pas de liste de cr
		}
	}

	// Cration de la liste
	glNewList(m_ListID, GL_COMPILE_AND_EXECUTE);
		// Affichage des lments de la collection
		GlDraw();
	glEndList();

	// Validit de la liste
	m_ListIsValid= true;

	//qDebug("GLC_Collection::CreateList : Liste d'affichage %u cr", m_ListID);

	// Gestion erreur OpenGL
	GLenum errCode;
	if ((errCode= glGetError()) != GL_NO_ERROR)
	{
		const GLubyte* errString;
		errString = gluErrorString(errCode);
		qDebug("GLC_Collection::CreationListe ERREUR OPENGL %s\n", errString);
	}

	return true;	// Gomtrie affich et liste cr

}
<|endoftext|>


<commit_before>/**
 * CameraTool.cpp
 * Created by Jerry Fan, property of The University of Auckland.
 * Licenced under the Artistic Licence 2.0.
 *
 * This utility runs mediainfo on videos inside a folder to determine their total
 * length.
 */

#include "./includes/LensCalibration.hpp"
#include "./includes/PerspectiveCalibration.hpp"
#include "./includes/ImageDistance.hpp"

#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/videoio.hpp>

#include <sstream>
#include <string>
#include <iostream>
#include <memory>

using namespace std;
using namespace cv;

/**
 * Function to extract frames from a video.
 * JSON output gives the video FPS.
 * @param src Source video file.
 * @param dst Destination directory.
 */
void extractImages(string src, string dst)
{
    VideoCapture video(src);
    if (video.isOpened())
    {
        Mat frame;
        int frameCount = 0;

		auto fps = video.get(CAP_PROP_FPS);

        if
        (
            dst.substr(dst.length() - 1, 1) != "/" ||
            dst.substr(dst.length() - 1, 1) != "\\"
        )
        {
            dst += "/";
        }

        while(true)
        {
            video >> frame;
            if (!frame.empty())
            {
                frameCount++;

                string filename = to_string(frameCount);
                imwrite(dst + filename + ".jpg", frame);
            }
            else
            {
                break;
            }
        }

        cout << "{\"fps\":" << fps << "}";
    }
}

/**
 * Performs lens calibration using OpenCV on a calibration video and saves a
 * calibration file.
 * @param src    Source video.
 * @param dst    Destination markup file (.xml or .yaml extension required).
 * @param frames Number of valid calibration frames (Don't use over 50).
 */
void lensCalibrationF(string src, string dst, string frames)
{
    LensCalibration lCalib;
    if (lCalib.fromVideo(src, (size_t) stoi(frames)))
    {
        lCalib.store(dst);
    }
}

/**
 * Removes lens distortion on an image based on a calibration file.
 * @param src       Source image.
 * @param dst       Destination image (valid extension required).
 * @param calibFile Calibration file.
 */
void lensCalibrationI(string src, string dst, string calibFile)
{
    LensCalibration lCalib;
    if (lCalib.fromFile(calibFile))
    {
        Mat M;
        if (lCalib.generateMaps())
        {
            if(lCalib.onImage(src, M))
            {
                imwrite(dst, M);
            }
        }
    }
}

/**
 * Removes lens distortion on a point based on a calibration file.
 * @param x         Image space x.
 * @param y         Image space y.
 * @param calibFile Calibration file.
 */
void lensCalibrationP(string x, string y, string calibFile)
{
    LensCalibration lCalib;
    if (lCalib.fromFile(calibFile))
    {
        if (lCalib.generateMaps())
        {
            Point2f transformed = lCalib.onPoint(Point2f(stof(x), stof(y)));
            cout << "{\"x\":" << transformed.x << ",\"y\":" << transformed.y << "}";
        }
    }
}

/**
 * Creates perspective calibration files from source points in image space and
 * the real world size of the planar rectangle specified from the source points.
 * @param tLPtsSrcX  Source quadrilateral top left x.
 * @param tLPtsSrcY  Source quadrilateral top left y.
 * @param tRPtsSrcX  Source quadrilateral top right x.
 * @param tRPtsSrcY  Source quadrilateral top right y.
 * @param bLPtsSrcX  Source quadrilateral bottom left x.
 * @param bLPtsSrcY  Source quadrilateral bottom left y.
 * @param bRPtsSrcX  Source quadrilateral bottom right x.
 * @param bRPtsSrcY  Source quadrilateral bottom right y.
 * @param ratioX     Real length of the planar rectangle.
 * @param ratioY     Real width of the planar rectangle.
 * @param outFile    Output calibration file (.xml or .yaml extension).
 */
void perspectiveCalibrationF
(
    string tLPtsSrcX, string tLPtsSrcY,
    string tRPtsSrcX, string tRPtsSrcY,
    string bLPtsSrcX, string bLPtsSrcY,
    string bRPtsSrcX, string bRPtsSrcY,
    string ratioX, string ratioY,
    string outFile
)
{
    vector<Point2f> ptsSrc;
    ptsSrc.push_back(Point2f(stof(tLPtsSrcX), stof(tLPtsSrcY)));
    ptsSrc.push_back(Point2f(stof(tRPtsSrcX), stof(tRPtsSrcY)));
    ptsSrc.push_back(Point2f(stof(bLPtsSrcX), stof(bLPtsSrcY)));
    ptsSrc.push_back(Point2f(stof(bRPtsSrcX), stof(bRPtsSrcY)));

    Point2f ratio(stof(ratioX), stof(ratioY));

    PerspectiveCalibration pCalib;

    vector<Point2f> ptsDst = pCalib.estimateTransformed(ptsSrc, ratio, Point2f(0,0));

    Mat M;
    pCalib.fromPoints(ptsSrc, ratio);
    pCalib.store(outFile);
}

/**
 * Performs perspective distortion correction on an image based on a calibraiton
 * file.
 * @param src       Source image file.
 * @param dst       Destination image file (with valid extension).
 * @param calibFile Calibration file.
 */
void perspectiveCalibrationI(string src, string dst, string calibFile)
{
    PerspectiveCalibration pCalib;

    Mat M;
    pCalib.fromFile(calibFile);
    pCalib.onImage(src, M);

    imwrite(dst, M);
}

/**
 * Performs perspective distortion correction on a point based on a calibration
 * file.
 * @param x         Image x.
 * @param y         Image y.
 * @param calibFile Calibration file.
 */
void perspectiveCalibrationP(string x, string y, string calibFile)
{
    PerspectiveCalibration pCalib;

    if (pCalib.fromFile(calibFile))
    {
        Point2f transformed = pCalib.onPoint(Point2f(stof(x), stof(y)));
        cout << "{\"x\":" << transformed.x << ",\"y\":" << transformed.y << "}";
    }
}

/**
 * Finds the coordinate of the specified point based on a virtual coordinate
 * system constructed using the calibration files, with the user defined origin
 * as the origin (0, 0).
 * @param x          Image x.
 * @param y          Image y.
 * @param originX    Image origin x.
 * @param originY    Image origin y.
 * @param lCalibFile Lens calibration file.
 * @param pCalibFile Perspective calibration file.
 */
void imageDistanceP
(
    string x, string y,
    string originX, string originY,
    string lCalibFile,
    string pCalibFile
)
{
    shared_ptr<LensCalibration> l = make_shared<LensCalibration>(lCalibFile);
    shared_ptr<PerspectiveCalibration> p = make_shared<PerspectiveCalibration>(pCalibFile);
    ImageDistance imgDst(l, p, Point2f(stof(originX), stof(originY)));

    Point2f transformed = imgDst.getRealCoordinate(Point2f(stof(x), stof(y)));

    cout << "{\"x\":" << transformed.x << ",\"y\":" << transformed.y << "}";
}

/**
 * Finds the distance between two points in real world distance based on a
 * virtual coordinate system constructed using the calibration files.
 * @param startX     Image first point x.
 * @param startY     Image first point y.
 * @param endX       Image second point x.
 * @param endY       Image second point y.
 * @param lCalibFile Lens calibration file.
 * @param pCalibFile Perspective calibration file.
 */
void imageDistanceD
(
    string startX, string startY,
    string endX, string endY,
    string lCalibFile, string pCalibFile
)
{
    shared_ptr<LensCalibration> l = make_shared<LensCalibration>(lCalibFile);
    shared_ptr<PerspectiveCalibration> p = make_shared<PerspectiveCalibration>(pCalibFile);

    ImageDistance imgDst(l, p);

    double distance = imgDst.getRealDistance(Point2f(stof(startX), stof(startY)), Point2f(stof(endX), stof(endY)));

    cout << "{\"distance\":" << distance << "}";
}

int main(int argc, char** argv)
{
    string option = argv[1];
    if (option == "-E")
    {
        extractImages(argv[2], argv[3]);
    }
    else if (option == "-Lf")
    {
        lensCalibrationF(argv[2], argv[3], argv[4]);
    }
    else if (option == "-Li")
    {
        lensCalibrationI(argv[2], argv[3], argv[4]);
    }
    else if (option == "-Lp")
    {
        lensCalibrationP(argv[2], argv[3], argv[4]);
    }
    else if (option == "-Pf")
    {
        perspectiveCalibrationF
        (
            argv[2], argv[3],
            argv[4], argv[5],
            argv[6], argv[7],
            argv[8], argv[9],
            argv[10], argv[11],
            argv[12]
        );
    }
    else if (option == "-Pi")
    {
        perspectiveCalibrationI(argv[2], argv[3], argv[4]);
    }
    else if (option == "-Pp")
    {
        perspectiveCalibrationP(argv[2], argv[3], argv[4]);
    }
    else if (option == "-Ip")
    {
        imageDistanceP
        (
            argv[2], argv[3],
            argv[4], argv[5],
            argv[6], argv[7]
        );
    }
    else if (option == "-Id")
    {
        imageDistanceD
        (
            argv[2], argv[3],
            argv[4], argv[5],
            argv[5], argv[6]
        );
    }
}
<commit_msg>Header was incorrect.<commit_after>/**
 * CameraTool.cpp
 * Created by Jerry Fan, property of The University of Auckland.
 * Licenced under the Artistic Licence 2.0.
 *
 * This tool interfaces with the calibration and distance C++ modules for a range
 * of purposes, including providing an interface for inferring a coordinate for
 * the Annotation-Tool using JSON to pass data, and to create the calibration files
 * from source material.
 */

#include "./includes/LensCalibration.hpp"
#include "./includes/PerspectiveCalibration.hpp"
#include "./includes/ImageDistance.hpp"

#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/videoio.hpp>

#include <sstream>
#include <string>
#include <iostream>
#include <memory>

using namespace std;
using namespace cv;

/**
 * Function to extract frames from a video.
 * JSON output gives the video FPS.
 * @param src Source video file.
 * @param dst Destination directory.
 */
void extractImages(string src, string dst)
{
    VideoCapture video(src);
    if (video.isOpened())
    {
        Mat frame;
        int frameCount = 0;

		auto fps = video.get(CAP_PROP_FPS);

        if
        (
            dst.substr(dst.length() - 1, 1) != "/" ||
            dst.substr(dst.length() - 1, 1) != "\\"
        )
        {
            dst += "/";
        }

        while(true)
        {
            video >> frame;
            if (!frame.empty())
            {
                frameCount++;

                string filename = to_string(frameCount);
                imwrite(dst + filename + ".jpg", frame);
            }
            else
            {
                break;
            }
        }

        cout << "{\"fps\":" << fps << "}";
    }
}

/**
 * Performs lens calibration using OpenCV on a calibration video and saves a
 * calibration file.
 * @param src    Source video.
 * @param dst    Destination markup file (.xml or .yaml extension required).
 * @param frames Number of valid calibration frames (Don't use over 50).
 */
void lensCalibrationF(string src, string dst, string frames)
{
    LensCalibration lCalib;
    if (lCalib.fromVideo(src, (size_t) stoi(frames)))
    {
        lCalib.store(dst);
    }
}

/**
 * Removes lens distortion on an image based on a calibration file.
 * @param src       Source image.
 * @param dst       Destination image (valid extension required).
 * @param calibFile Calibration file.
 */
void lensCalibrationI(string src, string dst, string calibFile)
{
    LensCalibration lCalib;
    if (lCalib.fromFile(calibFile))
    {
        Mat M;
        if (lCalib.generateMaps())
        {
            if(lCalib.onImage(src, M))
            {
                imwrite(dst, M);
            }
        }
    }
}

/**
 * Removes lens distortion on a point based on a calibration file.
 * @param x         Image space x.
 * @param y         Image space y.
 * @param calibFile Calibration file.
 */
void lensCalibrationP(string x, string y, string calibFile)
{
    LensCalibration lCalib;
    if (lCalib.fromFile(calibFile))
    {
        if (lCalib.generateMaps())
        {
            Point2f transformed = lCalib.onPoint(Point2f(stof(x), stof(y)));
            cout << "{\"x\":" << transformed.x << ",\"y\":" << transformed.y << "}";
        }
    }
}

/**
 * Creates perspective calibration files from source points in image space and
 * the real world size of the planar rectangle specified from the source points.
 * @param tLPtsSrcX  Source quadrilateral top left x.
 * @param tLPtsSrcY  Source quadrilateral top left y.
 * @param tRPtsSrcX  Source quadrilateral top right x.
 * @param tRPtsSrcY  Source quadrilateral top right y.
 * @param bLPtsSrcX  Source quadrilateral bottom left x.
 * @param bLPtsSrcY  Source quadrilateral bottom left y.
 * @param bRPtsSrcX  Source quadrilateral bottom right x.
 * @param bRPtsSrcY  Source quadrilateral bottom right y.
 * @param ratioX     Real length of the planar rectangle.
 * @param ratioY     Real width of the planar rectangle.
 * @param outFile    Output calibration file (.xml or .yaml extension).
 */
void perspectiveCalibrationF
(
    string tLPtsSrcX, string tLPtsSrcY,
    string tRPtsSrcX, string tRPtsSrcY,
    string bLPtsSrcX, string bLPtsSrcY,
    string bRPtsSrcX, string bRPtsSrcY,
    string ratioX, string ratioY,
    string outFile
)
{
    vector<Point2f> ptsSrc;
    ptsSrc.push_back(Point2f(stof(tLPtsSrcX), stof(tLPtsSrcY)));
    ptsSrc.push_back(Point2f(stof(tRPtsSrcX), stof(tRPtsSrcY)));
    ptsSrc.push_back(Point2f(stof(bLPtsSrcX), stof(bLPtsSrcY)));
    ptsSrc.push_back(Point2f(stof(bRPtsSrcX), stof(bRPtsSrcY)));

    Point2f ratio(stof(ratioX), stof(ratioY));

    PerspectiveCalibration pCalib;

    vector<Point2f> ptsDst = pCalib.estimateTransformed(ptsSrc, ratio, Point2f(0,0));

    Mat M;
    pCalib.fromPoints(ptsSrc, ratio);
    pCalib.store(outFile);
}

/**
 * Performs perspective distortion correction on an image based on a calibraiton
 * file.
 * @param src       Source image file.
 * @param dst       Destination image file (with valid extension).
 * @param calibFile Calibration file.
 */
void perspectiveCalibrationI(string src, string dst, string calibFile)
{
    PerspectiveCalibration pCalib;

    Mat M;
    pCalib.fromFile(calibFile);
    pCalib.onImage(src, M);

    imwrite(dst, M);
}

/**
 * Performs perspective distortion correction on a point based on a calibration
 * file.
 * @param x         Image x.
 * @param y         Image y.
 * @param calibFile Calibration file.
 */
void perspectiveCalibrationP(string x, string y, string calibFile)
{
    PerspectiveCalibration pCalib;

    if (pCalib.fromFile(calibFile))
    {
        Point2f transformed = pCalib.onPoint(Point2f(stof(x), stof(y)));
        cout << "{\"x\":" << transformed.x << ",\"y\":" << transformed.y << "}";
    }
}

/**
 * Finds the coordinate of the specified point based on a virtual coordinate
 * system constructed using the calibration files, with the user defined origin
 * as the origin (0, 0).
 * @param x          Image x.
 * @param y          Image y.
 * @param originX    Image origin x.
 * @param originY    Image origin y.
 * @param lCalibFile Lens calibration file.
 * @param pCalibFile Perspective calibration file.
 */
void imageDistanceP
(
    string x, string y,
    string originX, string originY,
    string lCalibFile,
    string pCalibFile
)
{
    shared_ptr<LensCalibration> l = make_shared<LensCalibration>(lCalibFile);
    shared_ptr<PerspectiveCalibration> p = make_shared<PerspectiveCalibration>(pCalibFile);
    ImageDistance imgDst(l, p, Point2f(stof(originX), stof(originY)));

    Point2f transformed = imgDst.getRealCoordinate(Point2f(stof(x), stof(y)));

    cout << "{\"x\":" << transformed.x << ",\"y\":" << transformed.y << "}";
}

/**
 * Finds the distance between two points in real world distance based on a
 * virtual coordinate system constructed using the calibration files.
 * @param startX     Image first point x.
 * @param startY     Image first point y.
 * @param endX       Image second point x.
 * @param endY       Image second point y.
 * @param lCalibFile Lens calibration file.
 * @param pCalibFile Perspective calibration file.
 */
void imageDistanceD
(
    string startX, string startY,
    string endX, string endY,
    string lCalibFile, string pCalibFile
)
{
    shared_ptr<LensCalibration> l = make_shared<LensCalibration>(lCalibFile);
    shared_ptr<PerspectiveCalibration> p = make_shared<PerspectiveCalibration>(pCalibFile);

    ImageDistance imgDst(l, p);

    double distance = imgDst.getRealDistance(Point2f(stof(startX), stof(startY)), Point2f(stof(endX), stof(endY)));

    cout << "{\"distance\":" << distance << "}";
}

int main(int argc, char** argv)
{
    string option = argv[1];
    if (option == "-E")
    {
        extractImages(argv[2], argv[3]);
    }
    else if (option == "-Lf")
    {
        lensCalibrationF(argv[2], argv[3], argv[4]);
    }
    else if (option == "-Li")
    {
        lensCalibrationI(argv[2], argv[3], argv[4]);
    }
    else if (option == "-Lp")
    {
        lensCalibrationP(argv[2], argv[3], argv[4]);
    }
    else if (option == "-Pf")
    {
        perspectiveCalibrationF
        (
            argv[2], argv[3],
            argv[4], argv[5],
            argv[6], argv[7],
            argv[8], argv[9],
            argv[10], argv[11],
            argv[12]
        );
    }
    else if (option == "-Pi")
    {
        perspectiveCalibrationI(argv[2], argv[3], argv[4]);
    }
    else if (option == "-Pp")
    {
        perspectiveCalibrationP(argv[2], argv[3], argv[4]);
    }
    else if (option == "-Ip")
    {
        imageDistanceP
        (
            argv[2], argv[3],
            argv[4], argv[5],
            argv[6], argv[7]
        );
    }
    else if (option == "-Id")
    {
        imageDistanceD
        (
            argv[2], argv[3],
            argv[4], argv[5],
            argv[5], argv[6]
        );
    }
}
<|endoftext|>