<commit_before>//////////////////////////////////////////////////////////////////////
//
//                             Pixie
//
// Copyright  1999 - 2003, Okan Arikan
//
// Contact: okan@cs.utexas.edu
//
//	This library is free software; you can redistribute it and/or
//	modify it under the terms of the GNU Lesser General Public
//	License as published by the Free Software Foundation; either
//	version 2.1 of the License, or (at your option) any later version.
//
//	This library is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//	Lesser General Public License for more details.
//
//	You should have received a copy of the GNU Lesser General Public
//	License along with this library; if not, write to the Free Software
//	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//
//  File				:	pointCloud.cpp
//  Classes				:	CPointCloud
//  Description			:	Implementation - George
//
////////////////////////////////////////////////////////////////////////
#include <math.h>

#include "pointCloud.h"
#include "object.h"
#include "raytracer.h"
#include "memory.h"
#include "random.h"
#include "error.h"

///////////////////////////////////////////////////////////////////////
// globals
///////////////////////////////////////////////////////////////////////

int			CPointCloud::drawDiscs		=	TRUE;
int			CPointCloud::drawChannel	=	0;

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	CPointCloud
// Description			:	Ctor
// Return Value			:
// Comments				:	for a write-mode map, ch and nc must be provided
CPointCloud::CPointCloud(const char *n,const float *from,const float *to,const float *toNDC,const char *channelDefs,int write) : CMap<CPointCloudPoint>(), CTexture3d(n,from,to,toNDC) {
	// Create our data areas
	flush				=	write;
	maxdP				=	0;

	osCreateMutex(mutex);

	// Assign the channels
	defineChannels(channelDefs);

	// Make sure we have a root
	// (but only if we're looking up, otherwise we'd add duff data)
	if (!write) balance();
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	CPointCloud
// Description			:	Ctor
// Return Value			:
// Comments				:	for a write-mode map via ptcapi, ch and nc must be provided
CPointCloud::CPointCloud(const char *n,const float *from,const float *to,const float *toNDC,int numChannels,char **channelNames,char **channelTypes,int write) : CMap<CPointCloudPoint>(), CTexture3d(n,from,to,toNDC) {
	// Create our data areas
	flush				=	write;
	maxdP				=	0;

	osCreateMutex(mutex);

	// Assign the channels
	defineChannels(numChannels,channelNames,channelTypes);

	// Make sure we have a root
	// (but only if we're looking up, otherwise we'd add duff data)
	if (!write) balance();
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	CPointCloud
// Description			:	Ctor
// Return Value			:
// Comments				:	for a write-mode map, ch and nc must be provided
CPointCloud::CPointCloud(const char *n,const float *from,const float *to,FILE *in) : CMap<CPointCloudPoint>(), CTexture3d(n,from,to) {

	// Create our data areas
	flush	=	FALSE;
	maxdP	=	0;

	osCreateMutex(mutex);

	// Try to read the point cloud

	// Read the header
	readChannels(in);

	// Read the points
	CMap<CPointCloudPoint>::read(in);

	// Reserve the actual space
	data.reserve(numItems*dataSize);

	// Read the data
	fread(data.array,sizeof(float),numItems*dataSize,in);
	data.numItems	=	numItems*dataSize;

	// Read the maximum radius
	fread(&maxdP,sizeof(float),1,in);

	// Close the file
	fclose(in);
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	~CPointCloud
// Description			:	Dtor
// Return Value			:
// Comments				:
CPointCloud::~CPointCloud() {
	osDeleteMutex(mutex);

	if (flush) write();
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	reset
// Description			:	Reset the photonmap
// Return Value			:
// Comments				:
void	CPointCloud::reset() {
	osLock(mutex);
	CMap<CPointCloudPoint>::reset();
	osUnlock(mutex);
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	write
// Description			:	Write the photon map into a file
// Return Value			:
// Comments				:
void	CPointCloud::write() {
	// Flush the photonmap
	FILE		*out		=	ropen(name,"wb",filePointCloud);

	if (out != NULL) {

		// Balance the map
		balance();

		// Write out the header and channels
		writeChannels(out);

		// Write the map
		CMap<CPointCloudPoint>::write(out);

		// Write the data
		fwrite(data.array,sizeof(float),numItems*dataSize,out);

		// Read the maximum radius
		fwrite(&maxdP,sizeof(float),1,out);

		// Close the file
		fclose(out);
	} else {
		error(CODE_BADFILE,"Unable to open %s for writing\n",name);
	}
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	lookup
// Description			:	Locate the nearest points
// Return Value			:
// Comments				:	Nl	must be normalized
//							Il	must be normalized
void	CPointCloud::lookup(float *Cl,const float *Pl,const float *Nl,float radius) {
	const int 				maxFound	=	16;
	const CPointCloudPoint	**indices	=	(const CPointCloudPoint **)	alloca((maxFound+1)*sizeof(CPointCloudPoint *));
	float					*distances	=	(float	*)					alloca((maxFound+1)*sizeof(float));
	CPointLookup			l;
	int						i,j;
	const float				scale		=	2.5f;	// By controlling this, we

	distances[0]		=	maxdP*maxdP*scale*scale;
	l.maxFound			=	maxFound;
	l.numFound			=	0;
	l.ignoreNormal		=	dotvv(Nl,Nl) == 0;

	// Perform lookup in the world coordinate system
	mulmp(l.P,to,Pl);
	mulmn(l.N,from,Nl);
	mulvf(l.N,-1);				// Photonmaps have N reversed, we must reverse
								// N when looking up it it
	normalizevf(l.N);

	l.gotHeap			=	FALSE;
	l.indices			=	indices;
	l.distances			=	distances;

	// No need to lock the mutex here, CMap::lookup is thread safe
	lookup(&l,1,scale);

	for (i=0;i<dataSize;i++) Cl[i] = 0.0f;	//GSHTODO: channel fill values

	if (l.numFound < 2)	return;

	int		numFound		=	l.numFound;
	float	totalWeight		=	0;

	for (i=1;i<=numFound;i++) {
		const	CPointCloudPoint	*p	=	indices[i];

		assert(distances[i] <= distances[0]);

		const float	t		=	sqrtf(distances[i]) / (p->dP*scale);
		const float	weight	=	(1-t)*(-dotvv(l.N,p->N));

		float		*dest	=	Cl;
		const float	*src	=	data.array + p->entryNumber;
		for (j=0;j<dataSize;j++) {
			*dest++			+=	(*src++)*weight;
		}
		totalWeight += weight;
	}

	if (totalWeight > 0) {
		// Divide the contribution
		const float weight	= 1.0f/totalWeight;
		for (i=0;i<dataSize;i++) Cl[i]	*=	weight;
	}
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	balance
// Description			:	Balance the map
// Return Value			:
// Comments				:
void	CPointCloud::balance() {
	// If we have no points in the map, add a dummy one to avoid an if statement during the lookup
	if (numItems == 0) {
		vector	P		=	{0,0,0};
		vector	N		=	{0,0,0};
		float	*data	=	(float*) alloca(dataSize*sizeof(float));

		for (int i=0;i<dataSize;i++)	data[i] = 0;

		// Store the fake data
		store(data,P,N,0);
	}

	// Balance the data
	CMap<CPointCloudPoint>::balance();
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	store
// Description			:	Store a photon
// Return Value			:
// Comments				:
void	CPointCloud::store(const float *C,const float *cP,const float *cN,float dP) {
	vector				P,N;
	CPointCloudPoint	*point;

	// Store in the world coordinate system
	mulmp(P,to,cP);
	mulmn(N,from,cN);
	dP					*=	dPscale;

	osLock(mutex);	// FIXME: use rwlock to allow multiple readers
	point				=	CMap<CPointCloudPoint>::store(P,N);
	point->entryNumber	=	data.numItems;
	point->dP			=	dP;

	for (int i=0;i<dataSize;i++)	data.push(C[i]);

	maxdP				=	max(maxdP,dP);

	osUnlock(mutex);
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	getPoint
// Description			:	Retrieve an indexed point
// Return Value			:
// Comments				:
void	CPointCloud::getPoint(int i,float *C,float *P,float *N,float *dP) {
	const	CPointCloudPoint	*p		=	items + i;
	const float 				*src	=	data.array + p->entryNumber;
	float						*dest	=	C;

	for (int j=0;j<dataSize;j++) {
		*dest++		=	*src++;
	}

	movvv(P,p->P);
	movvv(N,p->N);
	dP[0] = p->dP;
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	draw
// Description			:	Gui interface
// Return Value			:
// Comments				:
void	CPointCloud::draw() {
	float		P[chunkSize*3];
	float		C[chunkSize*3];
	float		N[chunkSize*3];
	float		dP[chunkSize];
	int			i,j;
	int			sampleStart		=	channels[drawChannel].sampleStart;
	int			numSamples		=	channels[drawChannel].numSamples;
	float		*cP				=	P;
	float		*cC				=	C;
	float		*cN				=	N;
	float		*cdP			=	dP;
	CPointCloudPoint	*cT		=	items+1;

	// Collect and dispatch the photons
	for (i=numItems,j=chunkSize;i>0;i--,cT++,cP+=3,cdP++,cN+=3,cC+=3,j--) {
		if (j == 0)	{
			if (drawDiscs)		drawDisks(chunkSize,P,dP,N,C);
			else			 	drawPoints(chunkSize,P,C);
			cP	=	P;
			cC	=	C;
			cN	=	N;
			cdP	=	dP;
			j	=	chunkSize;
		}

		movvv(cP,cT->P);
		movvv(cN,cT->N);
		*cdP	=	cT->dP;		// was /dPscale;	but should already be in world

		float *DDs = data.array + cT->entryNumber + sampleStart;
		if (numSamples == 1) {
			initv(cC,DDs[0]);
		} else if (numSamples == 2) {
			initv(cC,DDs[0],DDs[1],0);
		} else {
			movvv(cC,DDs);
		}
	}

	if (j != chunkSize) {
		if (drawDiscs)		drawDisks(chunkSize-j,P,dP,N,C);
		else			 	drawPoints(chunkSize-j,P,C);
	}
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	keyDown
// Description			:	handle keypresses
// Return Value			:	-
// Comments				:
int			CPointCloud::keyDown(int key) {
	if ((key == 'd') || (key == 'D')) {
		drawDiscs = TRUE;
		return TRUE;
	} else if ((key == 'p') || (key == 'P')) {
		drawDiscs = FALSE;
		return TRUE;
	} else if ((key == 'q') || (key == 'Q')) {
		drawChannel--;
		if (drawChannel < 0) drawChannel = 0;
		printf("channel : %s\n",channels[drawChannel].name);
		return TRUE;
	} else if ((key == 'w') || (key == 'W')) {
		drawChannel++;
		if (drawChannel >= numChannels) drawChannel = numChannels-1;
		printf("channel : %s\n",channels[drawChannel].name);
		return TRUE;
	}

	return FALSE;
}

//////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	draw
// Description			:	Gui interface
// Return Value			:
// Comments				:
void	CPointCloud::bound(float *bmin,float *bmax) {
	movvv(bmin,this->bmin);
	movvv(bmax,this->bmax);
}

<commit_msg>fixes for null normal (volume) lookup<commit_after>//////////////////////////////////////////////////////////////////////
//
//                             Pixie
//
// Copyright  1999 - 2003, Okan Arikan
//
// Contact: okan@cs.utexas.edu
//
//	This library is free software; you can redistribute it and/or
//	modify it under the terms of the GNU Lesser General Public
//	License as published by the Free Software Foundation; either
//	version 2.1 of the License, or (at your option) any later version.
//
//	This library is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//	Lesser General Public License for more details.
//
//	You should have received a copy of the GNU Lesser General Public
//	License along with this library; if not, write to the Free Software
//	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//
//  File				:	pointCloud.cpp
//  Classes				:	CPointCloud
//  Description			:	Implementation - George
//
////////////////////////////////////////////////////////////////////////
#include <math.h>

#include "pointCloud.h"
#include "object.h"
#include "raytracer.h"
#include "memory.h"
#include "random.h"
#include "error.h"

///////////////////////////////////////////////////////////////////////
// globals
///////////////////////////////////////////////////////////////////////

int			CPointCloud::drawDiscs		=	TRUE;
int			CPointCloud::drawChannel	=	0;

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	CPointCloud
// Description			:	Ctor
// Return Value			:
// Comments				:	for a write-mode map, ch and nc must be provided
CPointCloud::CPointCloud(const char *n,const float *from,const float *to,const float *toNDC,const char *channelDefs,int write) : CMap<CPointCloudPoint>(), CTexture3d(n,from,to,toNDC) {
	// Create our data areas
	flush				=	write;
	maxdP				=	0;

	osCreateMutex(mutex);

	// Assign the channels
	defineChannels(channelDefs);

	// Make sure we have a root
	// (but only if we're looking up, otherwise we'd add duff data)
	if (!write) balance();
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	CPointCloud
// Description			:	Ctor
// Return Value			:
// Comments				:	for a write-mode map via ptcapi, ch and nc must be provided
CPointCloud::CPointCloud(const char *n,const float *from,const float *to,const float *toNDC,int numChannels,char **channelNames,char **channelTypes,int write) : CMap<CPointCloudPoint>(), CTexture3d(n,from,to,toNDC) {
	// Create our data areas
	flush				=	write;
	maxdP				=	0;

	osCreateMutex(mutex);

	// Assign the channels
	defineChannels(numChannels,channelNames,channelTypes);

	// Make sure we have a root
	// (but only if we're looking up, otherwise we'd add duff data)
	if (!write) balance();
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	CPointCloud
// Description			:	Ctor
// Return Value			:
// Comments				:	for a write-mode map, ch and nc must be provided
CPointCloud::CPointCloud(const char *n,const float *from,const float *to,FILE *in) : CMap<CPointCloudPoint>(), CTexture3d(n,from,to) {

	// Create our data areas
	flush	=	FALSE;
	maxdP	=	0;

	osCreateMutex(mutex);

	// Try to read the point cloud

	// Read the header
	readChannels(in);

	// Read the points
	CMap<CPointCloudPoint>::read(in);

	// Reserve the actual space
	data.reserve(numItems*dataSize);

	// Read the data
	fread(data.array,sizeof(float),numItems*dataSize,in);
	data.numItems	=	numItems*dataSize;

	// Read the maximum radius
	fread(&maxdP,sizeof(float),1,in);

	// Close the file
	fclose(in);
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	~CPointCloud
// Description			:	Dtor
// Return Value			:
// Comments				:
CPointCloud::~CPointCloud() {
	osDeleteMutex(mutex);

	if (flush) write();
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	reset
// Description			:	Reset the photonmap
// Return Value			:
// Comments				:
void	CPointCloud::reset() {
	osLock(mutex);
	CMap<CPointCloudPoint>::reset();
	osUnlock(mutex);
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	write
// Description			:	Write the photon map into a file
// Return Value			:
// Comments				:
void	CPointCloud::write() {
	// Flush the photonmap
	FILE		*out		=	ropen(name,"wb",filePointCloud);

	if (out != NULL) {

		// Balance the map
		balance();

		// Write out the header and channels
		writeChannels(out);

		// Write the map
		CMap<CPointCloudPoint>::write(out);

		// Write the data
		fwrite(data.array,sizeof(float),numItems*dataSize,out);

		// Read the maximum radius
		fwrite(&maxdP,sizeof(float),1,out);

		// Close the file
		fclose(out);
	} else {
		error(CODE_BADFILE,"Unable to open %s for writing\n",name);
	}
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	lookup
// Description			:	Locate the nearest points
// Return Value			:
// Comments				:	Nl	must be normalized
//							Il	must be normalized
void	CPointCloud::lookup(float *Cl,const float *Pl,const float *Nl,float radius) {
	const int 				maxFound	=	16;
	const CPointCloudPoint	**indices	=	(const CPointCloudPoint **)	alloca((maxFound+1)*sizeof(CPointCloudPoint *));
	float					*distances	=	(float	*)					alloca((maxFound+1)*sizeof(float));
	CPointLookup			l;
	int						i,j;
	const float				scale		=	2.5f;	// By controlling this, we

	distances[0]		=	maxdP*maxdP*scale*scale;
	l.maxFound			=	maxFound;
	l.numFound			=	0;
	l.ignoreNormal		=	dotvv(Nl,Nl) < C_EPSILON;

	// Perform lookup in the world coordinate system
	mulmp(l.P,to,Pl);
	mulmn(l.N,from,Nl);
	mulvf(l.N,-1);				// Photonmaps have N reversed, we must reverse
								// N when looking up it it
	if (dotvv(Nl,Nl) > C_EPSILON) normalizevf(l.N);

	l.gotHeap			=	FALSE;
	l.indices			=	indices;
	l.distances			=	distances;

	// No need to lock the mutex here, CMap::lookup is thread safe
	lookup(&l,1,scale);

	for (i=0;i<dataSize;i++) Cl[i] = 0.0f;	//GSHTODO: channel fill values

	if (l.numFound < 2)	return;

	int		numFound		=	l.numFound;
	float	totalWeight		=	0;

	for (i=1;i<=numFound;i++) {
		const	CPointCloudPoint	*p	=	indices[i];

		assert(distances[i] <= distances[0]);

		const float	t		=	sqrtf(distances[i]) / (p->dP*scale);
		const float	weight	=	l.ignoreNormal ? (1-t) : (1-t)*(-dotvv(l.N,p->N));

		float		*dest	=	Cl;
		const float	*src	=	data.array + p->entryNumber;
		for (j=0;j<dataSize;j++) {
			*dest++			+=	(*src++)*weight;
		}
		totalWeight += weight;
	}

	if (totalWeight > 0) {
		// Divide the contribution
		const float weight	= 1.0f/totalWeight;
		for (i=0;i<dataSize;i++) Cl[i]	*=	weight;
	}
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	balance
// Description			:	Balance the map
// Return Value			:
// Comments				:
void	CPointCloud::balance() {
	// If we have no points in the map, add a dummy one to avoid an if statement during the lookup
	if (numItems == 0) {
		vector	P		=	{0,0,0};
		vector	N		=	{0,0,0};
		float	*data	=	(float*) alloca(dataSize*sizeof(float));

		for (int i=0;i<dataSize;i++)	data[i] = 0;

		// Store the fake data
		store(data,P,N,0);
	}

	// Balance the data
	CMap<CPointCloudPoint>::balance();
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	store
// Description			:	Store a photon
// Return Value			:
// Comments				:
void	CPointCloud::store(const float *C,const float *cP,const float *cN,float dP) {
	vector				P,N;
	CPointCloudPoint	*point;

	// Store in the world coordinate system
	mulmp(P,to,cP);
	mulmn(N,from,cN);
	dP					*=	dPscale;

	osLock(mutex);	// FIXME: use rwlock to allow multiple readers
	point				=	CMap<CPointCloudPoint>::store(P,N);
	point->entryNumber	=	data.numItems;
	point->dP			=	dP;

	for (int i=0;i<dataSize;i++)	data.push(C[i]);

	maxdP				=	max(maxdP,dP);

	osUnlock(mutex);
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	getPoint
// Description			:	Retrieve an indexed point
// Return Value			:
// Comments				:
void	CPointCloud::getPoint(int i,float *C,float *P,float *N,float *dP) {
	const	CPointCloudPoint	*p		=	items + i;
	const float 				*src	=	data.array + p->entryNumber;
	float						*dest	=	C;

	for (int j=0;j<dataSize;j++) {
		*dest++		=	*src++;
	}

	movvv(P,p->P);
	movvv(N,p->N);
	dP[0] = p->dP;
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	draw
// Description			:	Gui interface
// Return Value			:
// Comments				:
void	CPointCloud::draw() {
	float		P[chunkSize*3];
	float		C[chunkSize*3];
	float		N[chunkSize*3];
	float		dP[chunkSize];
	int			i,j;
	int			sampleStart		=	channels[drawChannel].sampleStart;
	int			numSamples		=	channels[drawChannel].numSamples;
	float		*cP				=	P;
	float		*cC				=	C;
	float		*cN				=	N;
	float		*cdP			=	dP;
	CPointCloudPoint	*cT		=	items+1;

	// Collect and dispatch the photons
	for (i=numItems,j=chunkSize;i>0;i--,cT++,cP+=3,cdP++,cN+=3,cC+=3,j--) {
		if (j == 0)	{
			if (drawDiscs)		drawDisks(chunkSize,P,dP,N,C);
			else			 	drawPoints(chunkSize,P,C);
			cP	=	P;
			cC	=	C;
			cN	=	N;
			cdP	=	dP;
			j	=	chunkSize;
		}

		movvv(cP,cT->P);
		movvv(cN,cT->N);
		*cdP	=	cT->dP;		// was /dPscale;	but should already be in world

		float *DDs = data.array + cT->entryNumber + sampleStart;
		if (numSamples == 1) {
			initv(cC,DDs[0]);
		} else if (numSamples == 2) {
			initv(cC,DDs[0],DDs[1],0);
		} else {
			movvv(cC,DDs);
		}
	}

	if (j != chunkSize) {
		if (drawDiscs)		drawDisks(chunkSize-j,P,dP,N,C);
		else			 	drawPoints(chunkSize-j,P,C);
	}
}

///////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	keyDown
// Description			:	handle keypresses
// Return Value			:	-
// Comments				:
int			CPointCloud::keyDown(int key) {
	if ((key == 'd') || (key == 'D')) {
		drawDiscs = TRUE;
		return TRUE;
	} else if ((key == 'p') || (key == 'P')) {
		drawDiscs = FALSE;
		return TRUE;
	} else if ((key == 'q') || (key == 'Q')) {
		drawChannel--;
		if (drawChannel < 0) drawChannel = 0;
		printf("channel : %s\n",channels[drawChannel].name);
		return TRUE;
	} else if ((key == 'w') || (key == 'W')) {
		drawChannel++;
		if (drawChannel >= numChannels) drawChannel = numChannels-1;
		printf("channel : %s\n",channels[drawChannel].name);
		return TRUE;
	}

	return FALSE;
}

//////////////////////////////////////////////////////////////////////
// Class				:	CPointCloud
// Method				:	draw
// Description			:	Gui interface
// Return Value			:
// Comments				:
void	CPointCloud::bound(float *bmin,float *bmax) {
	movvv(bmin,this->bmin);
	movvv(bmax,this->bmax);
}

<|endoftext|>


<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "rpcserver.h"
#include "main.h"
#include "kernel.h"
#include "checkpoints.h"

using namespace json_spirit;
using namespace std;

extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);

double GetDifficulty(const CBlockIndex* blockindex)
{
    // Floating point number that is a multiple of the minimum difficulty,
    // minimum difficulty = 1.0.
    if (blockindex == NULL)
    {
        if (pindexBest == NULL)
            return 1.0;
        else
            blockindex = GetLastBlockIndex(pindexBest, false);
    }

    int nShift = (blockindex->nBits >> 24) & 0xff;

    double dDiff =
        (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);

    while (nShift < 29)
    {
        dDiff *= 256.0;
        nShift++;
    }
    while (nShift > 29)
    {
        dDiff /= 256.0;
        nShift--;
    }

    return dDiff;
}

double GetPoWMHashPS()
{
    if (pindexBest->nHeight >= LAST_POW_TIME)
        return 0;

    int nPoWInterval = 72;
    int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;

    CBlockIndex* pindex = pindexGenesisBlock;
    CBlockIndex* pindexPrevWork = pindexGenesisBlock;

    while (pindex)
    {
        if (pindex->IsProofOfWork())
        {
            int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
            nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
            nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
            pindexPrevWork = pindex;
        }

        pindex = pindex->pnext;
    }

    return GetDifficulty() * 4294.967296 / nTargetSpacingWork;
}

double GetPoSKernelPS()
{
    int nPoSInterval = 72;
    double dStakeKernelsTriedAvg = 0;
    int nStakesHandled = 0, nStakesTime = 0;

    CBlockIndex* pindex = pindexBest;;
    CBlockIndex* pindexPrevStake = NULL;

    while (pindex && nStakesHandled < nPoSInterval)
    {
        if (pindex->IsProofOfStake())
        {
            if (pindexPrevStake)
            {
                dStakeKernelsTriedAvg += GetDifficulty(pindexPrevStake) * 4294967296.0;
                nStakesTime += pindexPrevStake->nTime - pindex->nTime;
                nStakesHandled++;
            }
            pindexPrevStake = pindex;
        }

        pindex = pindex->pprev;
    }

    double result = 0;

    if (nStakesTime)
        result = dStakeKernelsTriedAvg / nStakesTime;

    if (IsProtocolV2(nBestHeight))
        result *= STAKE_TIMESTAMP_MASK + 1;

    return result;
}

Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
{
    Object result;
    result.push_back(Pair("hash", block.GetHash().GetHex()));
    int confirmations = -1;
    // Only report confirmations if the block is on the main chain
    if (blockindex->IsInMainChain())
        confirmations = nBestHeight - blockindex->nHeight + 1;
    result.push_back(Pair("confirmations", confirmations));
    result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
    result.push_back(Pair("height", blockindex->nHeight));
    result.push_back(Pair("version", block.nVersion));
    result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
    result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
    result.push_back(Pair("time", (int64_t)block.GetBlockTime()));
    result.push_back(Pair("nonce", (uint64_t)block.nNonce));
    result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
    result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
    result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0')));
    result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0')));
    if (blockindex->pprev)
        result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
    if (blockindex->pnext)
        result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));

    result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
    result.push_back(Pair("proofhash", blockindex->hashProof.GetHex()));
    result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
    result.push_back(Pair("modifier", strprintf("%016x", blockindex->nStakeModifier)));
    result.push_back(Pair("modifierv2", blockindex->bnStakeModifierV2.GetHex()));
    Array txinfo;
    BOOST_FOREACH (const CTransaction& tx, block.vtx)
    {
        if (fPrintTransactionDetail)
        {
            Object entry;

            entry.push_back(Pair("txid", tx.GetHash().GetHex()));
            TxToJSON(tx, 0, entry);

            txinfo.push_back(entry);
        }
        else
            txinfo.push_back(tx.GetHash().GetHex());
    }

    result.push_back(Pair("tx", txinfo));

    if (block.IsProofOfStake())
        result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));

    return result;
}

Value getbestblockhash(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getbestblockhash\n"
            "Returns the hash of the best block in the longest block chain.");

    return hashBestChain.GetHex();
}

Value getblockcount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getblockcount\n"
            "Returns the number of blocks in the longest block chain.");

    return nBestHeight;
}

Value getdifficulty(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getdifficulty\n"
            "Returns the difficulty as a multiple of the minimum difficulty.");

    Object obj;
    obj.push_back(Pair("proof-of-work",        GetDifficulty()));
    obj.push_back(Pair("proof-of-stake",       GetDifficulty(GetLastBlockIndex(pindexBest, true))));
    return obj;
}

Value getrawmempool(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getrawmempool\n"
            "Returns all transaction ids in memory pool.");

    vector<uint256> vtxid;
    mempool.queryHashes(vtxid);

    Array a;
    BOOST_FOREACH(const uint256& hash, vtxid)
        a.push_back(hash.ToString());

    return a;
}

Value getblockhash(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "getblockhash <index>\n"
            "Returns hash of block in best-block-chain at <index>.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
    return pblockindex->phashBlock->GetHex();
}

Value getblock(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblock \"blockhash\" ( verbosity ) \n"
            "\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
            "If verbosity is 1, returns an Object with information about block <hash>.\n"
            "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n"
            "\nArguments:\n"
            "1. \"blockhash\"          (string, required) The block hash\n"
            "2. verbosity              (numeric, optional, default=1) 0 for hex encoded data, 1 for a json object, and 2 for json object with transaction data\n"
            "\nResult (for verbosity = 0):\n"
            "\"data\"             (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
            "\nResult (for verbosity = 1):\n"
            "{\n"
            "  \"hash\" : \"hash\",     (string) the block hash (same as provided)\n"
            "  \"confirmations\" : n,   (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
            "  \"size\" : n,            (numeric) The block size\n"
            "  \"strippedsize\" : n,    (numeric) The block size excluding witness data\n"
            "  \"weight\" : n           (numeric) The block weight as defined in BIP 141\n"
            "  \"height\" : n,          (numeric) The block height or index\n"
            "  \"version\" : n,         (numeric) The block version\n"
            "  \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
            "  \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
            "  \"tx\" : [               (array of string) The transaction ids\n"
            "     \"transactionid\"     (string) The transaction id\n"
            "     ,...\n"
            "  ],\n"
            "  \"time\" : ttt,          (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
            "  \"mediantime\" : ttt,    (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
            "  \"nonce\" : n,           (numeric) The nonce\n"
            "  \"bits\" : \"1d00ffff\", (string) The bits\n"
            "  \"difficulty\" : x.xxx,  (numeric) The difficulty\n"
            "  \"chainwork\" : \"xxxx\",  (string) Expected number of hashes required to produce the chain up to this block (in hex)\n"
            "  \"previousblockhash\" : \"hash\",  (string) The hash of the previous block\n"
            "  \"nextblockhash\" : \"hash\"       (string) The hash of the next block\n"
            "}\n"
            "\nResult (for verbosity = 2):\n"
            "{\n"
            "  ...,                     Same output as verbosity = 1.\n"
            "  \"tx\" : [               (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n"
            "         ,...\n"
            "  ],\n"
            "  ,...                     Same output as verbosity = 1.\n"
            "}\n"
            "\nExamples:\n"
        );

    LOCK(cs_main);

    std::string strHash = params[0].get_str();
    uint256 hash(strHash);

    int verbosity = 1;

	std::string check_verbosity = params[1].get_str();
    if (params.size() > 1) {
        //if(params[1].isNum())
		if(params[1].get_int())
            verbosity = params[1].get_int();
        else
            verbosity = params[1].get_bool() ? 1 : 0;
    }

    if (mapBlockIndex.count(hash) == 0)
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hash];

    if (verbosity <= 0)
    {
        CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
        ssBlock << block;
        std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
        return strHex;
    }

    return blockToJSON(block, pblockindex, verbosity >= 2);
}
Value getblockbynumber(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblockbynumber <number> [txinfo]\n"
            "txinfo optional to print more detailed tx info\n"
            "Returns details of a block with given block-number.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
    while (pblockindex->nHeight > nHeight)
        pblockindex = pblockindex->pprev;

    uint256 hash = *pblockindex->phashBlock;

    pblockindex = mapBlockIndex[hash];
    block.ReadFromDisk(pblockindex, true);

    return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}

// ppcoin: get information of sync-checkpoint
Value getcheckpoint(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getcheckpoint\n"
            "Show info of synchronized checkpoint.\n");

    Object result;
    const CBlockIndex* pindexCheckpoint = Checkpoints::AutoSelectSyncCheckpoint();

    result.push_back(Pair("synccheckpoint", pindexCheckpoint->GetBlockHash().ToString().c_str()));
    result.push_back(Pair("height", pindexCheckpoint->nHeight));
    result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));

    result.push_back(Pair("policy", "rolling"));

    return result;
}
<commit_msg>Updated getblock to the latest bitcoin build<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "rpcserver.h"
#include "main.h"
#include "kernel.h"
#include "checkpoints.h"

using namespace json_spirit;
using namespace std;

extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);

double GetDifficulty(const CBlockIndex* blockindex)
{
    // Floating point number that is a multiple of the minimum difficulty,
    // minimum difficulty = 1.0.
    if (blockindex == NULL)
    {
        if (pindexBest == NULL)
            return 1.0;
        else
            blockindex = GetLastBlockIndex(pindexBest, false);
    }

    int nShift = (blockindex->nBits >> 24) & 0xff;

    double dDiff =
        (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);

    while (nShift < 29)
    {
        dDiff *= 256.0;
        nShift++;
    }
    while (nShift > 29)
    {
        dDiff /= 256.0;
        nShift--;
    }

    return dDiff;
}

double GetPoWMHashPS()
{
    if (pindexBest->nHeight >= LAST_POW_TIME)
        return 0;

    int nPoWInterval = 72;
    int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;

    CBlockIndex* pindex = pindexGenesisBlock;
    CBlockIndex* pindexPrevWork = pindexGenesisBlock;

    while (pindex)
    {
        if (pindex->IsProofOfWork())
        {
            int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
            nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
            nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
            pindexPrevWork = pindex;
        }

        pindex = pindex->pnext;
    }

    return GetDifficulty() * 4294.967296 / nTargetSpacingWork;
}

double GetPoSKernelPS()
{
    int nPoSInterval = 72;
    double dStakeKernelsTriedAvg = 0;
    int nStakesHandled = 0, nStakesTime = 0;

    CBlockIndex* pindex = pindexBest;;
    CBlockIndex* pindexPrevStake = NULL;

    while (pindex && nStakesHandled < nPoSInterval)
    {
        if (pindex->IsProofOfStake())
        {
            if (pindexPrevStake)
            {
                dStakeKernelsTriedAvg += GetDifficulty(pindexPrevStake) * 4294967296.0;
                nStakesTime += pindexPrevStake->nTime - pindex->nTime;
                nStakesHandled++;
            }
            pindexPrevStake = pindex;
        }

        pindex = pindex->pprev;
    }

    double result = 0;

    if (nStakesTime)
        result = dStakeKernelsTriedAvg / nStakesTime;

    if (IsProtocolV2(nBestHeight))
        result *= STAKE_TIMESTAMP_MASK + 1;

    return result;
}

Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
{
    Object result;
    result.push_back(Pair("hash", block.GetHash().GetHex()));
    int confirmations = -1;
    // Only report confirmations if the block is on the main chain
    if (blockindex->IsInMainChain())
        confirmations = nBestHeight - blockindex->nHeight + 1;
    result.push_back(Pair("confirmations", confirmations));
    result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
    result.push_back(Pair("height", blockindex->nHeight));
    result.push_back(Pair("version", block.nVersion));
    result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
    result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
    result.push_back(Pair("time", (int64_t)block.GetBlockTime()));
    result.push_back(Pair("nonce", (uint64_t)block.nNonce));
    result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
    result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
    result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0')));
    result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0')));
    if (blockindex->pprev)
        result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
    if (blockindex->pnext)
        result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));

    result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
    result.push_back(Pair("proofhash", blockindex->hashProof.GetHex()));
    result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
    result.push_back(Pair("modifier", strprintf("%016x", blockindex->nStakeModifier)));
    result.push_back(Pair("modifierv2", blockindex->bnStakeModifierV2.GetHex()));
    Array txinfo;
    BOOST_FOREACH (const CTransaction& tx, block.vtx)
    {
        if (fPrintTransactionDetail)
        {
            Object entry;

            entry.push_back(Pair("txid", tx.GetHash().GetHex()));
            TxToJSON(tx, 0, entry);

            txinfo.push_back(entry);
        }
        else
            txinfo.push_back(tx.GetHash().GetHex());
    }

    result.push_back(Pair("tx", txinfo));

    if (block.IsProofOfStake())
        result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));

    return result;
}

Value getbestblockhash(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getbestblockhash\n"
            "Returns the hash of the best block in the longest block chain.");

    return hashBestChain.GetHex();
}

Value getblockcount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getblockcount\n"
            "Returns the number of blocks in the longest block chain.");

    return nBestHeight;
}

Value getdifficulty(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getdifficulty\n"
            "Returns the difficulty as a multiple of the minimum difficulty.");

    Object obj;
    obj.push_back(Pair("proof-of-work",        GetDifficulty()));
    obj.push_back(Pair("proof-of-stake",       GetDifficulty(GetLastBlockIndex(pindexBest, true))));
    return obj;
}

Value getrawmempool(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getrawmempool\n"
            "Returns all transaction ids in memory pool.");

    vector<uint256> vtxid;
    mempool.queryHashes(vtxid);

    Array a;
    BOOST_FOREACH(const uint256& hash, vtxid)
        a.push_back(hash.ToString());

    return a;
}

Value getblockhash(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "getblockhash <index>\n"
            "Returns hash of block in best-block-chain at <index>.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
    return pblockindex->phashBlock->GetHex();
}

Value getblock(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblock \"blockhash\" ( verbosity ) \n"
            "\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
            "If verbosity is 1, returns an Object with information about block <hash>.\n"
            "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n"
            "\nArguments:\n"
            "1. \"blockhash\"          (string, required) The block hash\n"
            "2. verbosity              (numeric, optional, default=1) 0 for hex encoded data, 1 for a json object, and 2 for json object with transaction data\n"
            "\nResult (for verbosity = 0):\n"
            "\"data\"             (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
            "\nResult (for verbosity = 1):\n"
            "{\n"
            "  \"hash\" : \"hash\",     (string) the block hash (same as provided)\n"
            "  \"confirmations\" : n,   (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
            "  \"size\" : n,            (numeric) The block size\n"
            "  \"strippedsize\" : n,    (numeric) The block size excluding witness data\n"
            "  \"weight\" : n           (numeric) The block weight as defined in BIP 141\n"
            "  \"height\" : n,          (numeric) The block height or index\n"
            "  \"version\" : n,         (numeric) The block version\n"
            "  \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
            "  \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
            "  \"tx\" : [               (array of string) The transaction ids\n"
            "     \"transactionid\"     (string) The transaction id\n"
            "     ,...\n"
            "  ],\n"
            "  \"time\" : ttt,          (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
            "  \"mediantime\" : ttt,    (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
            "  \"nonce\" : n,           (numeric) The nonce\n"
            "  \"bits\" : \"1d00ffff\", (string) The bits\n"
            "  \"difficulty\" : x.xxx,  (numeric) The difficulty\n"
            "  \"chainwork\" : \"xxxx\",  (string) Expected number of hashes required to produce the chain up to this block (in hex)\n"
            "  \"previousblockhash\" : \"hash\",  (string) The hash of the previous block\n"
            "  \"nextblockhash\" : \"hash\"       (string) The hash of the next block\n"
            "}\n"
            "\nResult (for verbosity = 2):\n"
            "{\n"
            "  ...,                     Same output as verbosity = 1.\n"
            "  \"tx\" : [               (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n"
            "         ,...\n"
            "  ],\n"
            "  ,...                     Same output as verbosity = 1.\n"
            "}\n"
            "\nExamples:\n"
        );

    LOCK(cs_main);

    //std::string strHash = params[0].get_str();
    //uint256 hash(strHash);
    std::string strHash = params[0].get_str();
	uint256 hash(uint256S(strHash));

    int verbosity = 1;
    if (params.size() > 1) {
            verbosity = params[1].get_bool() ? 1 : 0;
    }

    if (mapBlockIndex.count(hash) == 0)
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hash];

	if(!block.ReadFromDisk(pblockindex, true)){
        // Block not found on disk. This could be because we have the block
        // header in our index but don't have the block (for example if a
        // non-whitelisted node sends us an unrequested long chain of valid
        // blocks, we add the headers to our index, but don't accept the
        // block).
		throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
	}

	block.ReadFromDisk(pblockindex, true);

    if (verbosity <= 0)
    {
        CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
        ssBlock << block;
        std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
		//strHex.insert(0, "testar ");
        return strHex;
    }

    //return blockToJSON(block, pblockindex, verbosity >= 2);
	return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}
Value getblock_old(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblock <hash> [txinfo]\n"
            "txinfo optional to print more detailed tx info\n"
            "Returns details of a block with given block-hash.");

    std::string strHash = params[0].get_str();
    uint256 hash(strHash);

    if (mapBlockIndex.count(hash) == 0)
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hash];
    block.ReadFromDisk(pblockindex, true);

    return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}

Value getblockbynumber(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getblockbynumber <number> [txinfo]\n"
            "txinfo optional to print more detailed tx info\n"
            "Returns details of a block with given block-number.");

    int nHeight = params[0].get_int();
    if (nHeight < 0 || nHeight > nBestHeight)
        throw runtime_error("Block number out of range.");

    CBlock block;
    CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
    while (pblockindex->nHeight > nHeight)
        pblockindex = pblockindex->pprev;

    uint256 hash = *pblockindex->phashBlock;

    pblockindex = mapBlockIndex[hash];
    block.ReadFromDisk(pblockindex, true);

    return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}

// ppcoin: get information of sync-checkpoint
Value getcheckpoint(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getcheckpoint\n"
            "Show info of synchronized checkpoint.\n");

    Object result;
    const CBlockIndex* pindexCheckpoint = Checkpoints::AutoSelectSyncCheckpoint();

    result.push_back(Pair("synccheckpoint", pindexCheckpoint->GetBlockHash().ToString().c_str()));
    result.push_back(Pair("height", pindexCheckpoint->nHeight));
    result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));

    result.push_back(Pair("policy", "rolling"));

    return result;
}
<|endoftext|>


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

    Copyright (C) 2013 by Sajia Akhter, Edwards Lab, San Diego State University

    This file is part of Qudaich.

    Qudaich is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

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

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h> /* required for MAX_PATH */

void version(char *);
char *execpath(char *);
void inputError(const char *);
void help(char *);

int TOTAL_DB_SEQ = 0, TOTAL_QRY_SEQ = 0, LINE_LEN, SIZE_SEQ = 0, SIZE_SEQ_NAME = 0;
char mypath[PATH_MAX];

void inputError(const char *msg) {
  fprintf(stderr, "%s", msg);
  exit(-1);
}

/* return the path of the current executable so we can append bin to it
 * arg: exec is argv[0]
 * returns: a string representing the current path
 *
 * Uses realpath in stdlib.h and MAX_PATH in limits.h
 */
char *execpath(char *exec) {
	char *mp = realpath(exec, mypath); /*  this is the complete path */
	char *ptr = strrchr(mp, '/'); /* this is from the last / forwards - should be path separator! */
	int posn = strlen(mp) - strlen(ptr); /* the position of the last / */
	mypath[posn] = '\0';
	return mypath;
}

/* print out the version number and then the help menu. Note that we require argv[0] so we can pass it forward */
void version(char *p) {
	FILE * fp;
	char v[256];
	fp = fopen("VERSION", "r");
	if (fp != NULL) {
		char *check_fgets = fgets(v, 256, fp);
	}
	printf("\n%s %s\n", p, v);
	help(p);
}

/* help() prints the help menu and exits. Please provide argv[0] as an option so we can include that in the help menu */
void help(char * p) {
      printf("\n%s -q [query] -d [database] -p [program] or\n%s -query [query file] -db [database file] -prog [program]\n\n", p, p);
      printf("-q|-query                      Name of the query file (Required)\n");
      printf("-d|-db                         Name of database file (Required)\n");
      printf("-p|-prog                       Alignment options (Required):  n (nucleotide),\n");
      printf("                                                           p (protein),\n");
      printf("                                                           trn (translated nucleotide)\n");
      printf("                                                           trnx (translated nucleotide vs protein database)\n");
      printf("-t|-top                        Number of alignments per query sequence (default 1)\n");
      printf("-f|-freqFile                   Frequency file Name\n");
      printf("-c|-heuristic                  Heuristic options: 1 (default) or 2 (See the README or paper for more information)\n");
      printf("-h|-help                       Show command line options and exit\n");
      printf("-v|-version                    Print the version and help options and exit\n");
      exit(0);
}

int input_size(FILE *f, int flag)
{
  int L = 2000, SIZE = 0, t, max = 0, total_seq = 0, temp = 0, maxsize=0 ;
  char name[L];

  while(fgets(name,L,f)!=NULL)
  {
        if (name[0] == '>'){
		total_seq++;
		t = strlen(name);
		if(t>max) max = t;
		SIZE += temp;
		if (temp >  maxsize) maxsize = temp;
		temp = 0;
                continue;
	}
        else
	{
		t = strlen(name)-1;
		if((name[t]) != '\n')
            		t++;
                temp = temp + t;
	}
  }
  SIZE += temp;
  if (temp >  maxsize) maxsize = temp;

  if (flag == 0){//DB
	TOTAL_DB_SEQ = total_seq;
        if (SIZE_SEQ<maxsize) SIZE_SEQ = maxsize;
	if (SIZE_SEQ_NAME<max) SIZE_SEQ_NAME = max;
  }
  else//query
  {
 	TOTAL_QRY_SEQ = total_seq;
        if (SIZE_SEQ<maxsize) SIZE_SEQ = maxsize;
        if (SIZE_SEQ_NAME<max) SIZE_SEQ_NAME = max;
  }
  return SIZE;
}

int main(int argc, char **argv) {
  int i;
  char queryFile[1024], refFile[1024], outputfile[1024], program[16];
  int top = 1, hypothesis = 1;
  FILE *f;

  strcpy(outputfile, "freq.txt");

  for(i=1;i<argc;i++) {
    if(!strcmp(argv[i], "-query") || !strcmp(argv[i], "-q")) {
      if(i+1 >= argc) {
	inputError("Query File name required\n");
      }
      strcpy(queryFile, argv[i+1]);
      i++;
    }
    else if(!strcmp(argv[i], "-ref") || !strcmp(argv[i], "-db") || !strcmp(argv[i], "-d")) {
      if(i+1 >= argc) {
	inputError("Database File name required\n");
      }
      strcpy(refFile, argv[i+1]);
      i++;
    }
    else if(!strcmp(argv[i], "-prog") || !strcmp(argv[i], "-p")) {
      if(i+1 >= argc) {
        inputError("Alignment option required\n");
      }
      strcpy(program, argv[i+1]);
      if (strcmp(program,"n")!=0 and strcmp(program,"p")!=0 and strcmp(program,"trn")!=0 and strcmp(program,"trnx")!=0)
	inputError("Valid alignment option required\nPlease use -h for details information\n");
      i++;
    }

    else if(!strcmp(argv[i], "-freqFile") || !strcmp(argv[i], "-f")) {
      if(i+1 >= argc) {
        inputError("Frequency File name required\n");
      }
      strcpy(outputfile, argv[i+1]);
      i++;
    }
    else if(!strcmp(argv[i], "-hypo") || !strcmp(argv[i], "-heuristic") || !strcmp(argv[i], "-c")) {
      if(i+1 >= argc) {
        inputError("Argument required\n");
      }
      sscanf(argv[i+1], "%d", &hypothesis);
      if(hypothesis <= 0 || hypothesis >=3) {
        inputError("Value of the heuristic must be either 1 (default) or 2\n");
      }
      i++;
    }
    else if(!strcmp(argv[i], "-top")) {
      if(i+1 >= argc) {
	inputError("Argument required\n");
      }
      sscanf(argv[i+1], "%d", &top);
      if(top <= 0) {
	inputError("Value of top must be positive\n");
      }
      i++;
    }
    else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "-help"))
	    help(argv[0]);
    else if (!strcmp(argv[i], "-version") || !strcmp(argv[i], "-v"))
	    version(argv[0]);
    else {
      inputError("Invalid arguments\n");
      inputError(argv[i]);
    }
  }

  if(!queryFile[0] || !refFile[0] || !program[0]) {
    help(argv[0]);
  }

  // CHECK whether these are valid files
  unsigned int SIZEr = 0, SIZEq = 0, SIZE = 0;

  //read file:
  f = fopen(refFile,"r");
  SIZEr = input_size(f,0);
  fclose(f);
  f = fopen(queryFile,"r");
  SIZEq = input_size(f,1);
  fclose(f);

  char progBuf[1024],write_buff[1024];
  LINE_LEN = 2000;

  SIZE_SEQ++;
  SIZE_SEQ_NAME++;
  sprintf(write_buff,"%d %d %d %d %d", TOTAL_DB_SEQ, TOTAL_QRY_SEQ, LINE_LEN, SIZE_SEQ, SIZE_SEQ_NAME);

  char *app_path;
  if ((app_path = execpath(argv[0])) == NULL) {
	  fprintf(stderr, "ERROR: We can not get an application path from %s\n", argv[0]);
	  exit(-1);
  }

  if (strcmp(program,"n")==0)
  {
	SIZE = SIZEr * 2 + SIZEq + 2;
        if (SIZE >= 2000000000){
		 printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u)  * 2 + total query bp (%u)]\n",SIZE,SIZEr,SIZEq);
		inputError("");
	}

	if(hypothesis == 1)
	{
		if(top == 1)
			sprintf(progBuf, "%s/bin/search_dna_hypo1 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
		else
			sprintf(progBuf, "%s/bin/search_dna_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
	}
	else
	{
	        if(top == 1)
                        sprintf(progBuf, "%s/bin/search_dna_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
                else
                        sprintf(progBuf, "%s/bin/search_dna_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
	}
  }
  else if (strcmp(program,"p")==0)
  {
        SIZE = SIZEr + SIZEq + 2;
        if (SIZE >= 2000000000){
                          printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u) + total query bp (%u)]\n",SIZE,SIZEr,SIZEq);
                inputError("");
        }
	if(hypothesis == 1)
        {
                if(top == 1)
                        sprintf(progBuf, "%s/bin/search_pro_hypo1 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
                else
                        sprintf(progBuf, "%s/bin/search_pro_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
        }
        else
        {
                if(top == 1)
                        sprintf(progBuf, "%s/bin/search_pro_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
                else
                        sprintf(progBuf, "%s/bin/search_pro_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
        }
  }
  else if (strcmp(program,"trn")==0)
  {
        SIZE = SIZEr * 2 + SIZEq + 2;
        if (SIZE >= 2000000000) {
                          printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u)  * 2 + total query bp (%u)]\n",SIZE,SIZEr,SIZEq);
                inputError("");
        }
	if(hypothesis == 1)
        {
                if(top == 1)
                        sprintf(progBuf, "%s/bin/search_trn_hypo1 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
                else
                        sprintf(progBuf, "%s/bin/search_trn_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
        }
        else
        {
                if(top == 1)
                        sprintf(progBuf, "%s/bin/search_trn_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
                else
                        sprintf(progBuf, "%s/bin/search_trn_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
        }
  }

//////////////////
  else if (strcmp(program,"trnx")==0)
  {
        SIZE = SIZEr + SIZEq*2 + 2;
        if (SIZE >= 2000000000) {
                          printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u) + total query bp (%u) * 2]\n",SIZE,SIZEr,SIZEq);
                inputError("");
        }
        if(hypothesis == 1)
        {
                        sprintf(progBuf, "%s/bin/search_trnx_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
        }
        else
        {
		printf("Current version of Quadich supports only hypothesis I for translated nucleotide vs protein database alignmnet.\n\n");
                inputError("");
                /*if(top == 1)
                        sprintf(progBuf, "%s/bin/search_trn_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
                else
                        sprintf(progBuf, "%s/bin/search_trn_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);

	*/
        }
  }
  else{
        inputError("Please specify the correct program option\n");
      }

  printf("%s\n",progBuf);
  int returnval = system(progBuf);

  return returnval;
}

<commit_msg>correcting a -t for top<commit_after>/***********************************************************************************

    Copyright (C) 2013 by Sajia Akhter, Edwards Lab, San Diego State University

    This file is part of Qudaich.

    Qudaich is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

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

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h> /* required for MAX_PATH */

void version(char *);
char *execpath(char *);
void inputError(const char *);
void help(char *);

int TOTAL_DB_SEQ = 0, TOTAL_QRY_SEQ = 0, LINE_LEN, SIZE_SEQ = 0, SIZE_SEQ_NAME = 0;
char mypath[PATH_MAX];

void inputError(const char *msg) {
  fprintf(stderr, "%s", msg);
  exit(-1);
}

/* return the path of the current executable so we can append bin to it
 * arg: exec is argv[0]
 * returns: a string representing the current path
 *
 * Uses realpath in stdlib.h and MAX_PATH in limits.h
 */
char *execpath(char *exec) {
	char *mp = realpath(exec, mypath); /*  this is the complete path */
	char *ptr = strrchr(mp, '/'); /* this is from the last / forwards - should be path separator! */
	int posn = strlen(mp) - strlen(ptr); /* the position of the last / */
	mypath[posn] = '\0';
	return mypath;
}

/* print out the version number and then the help menu. Note that we require argv[0] so we can pass it forward */
void version(char *p) {
	FILE * fp;
	char v[256];
	fp = fopen("VERSION", "r");
	if (fp != NULL) {
		char *check_fgets = fgets(v, 256, fp);
	}
	printf("\n%s %s\n", p, v);
	help(p);
}

/* help() prints the help menu and exits. Please provide argv[0] as an option so we can include that in the help menu */
void help(char * p) {
      printf("\n%s -q [query] -d [database] -p [program] or\n%s -query [query file] -db [database file] -prog [program]\n\n", p, p);
      printf("-q|-query                      Name of the query file (Required)\n");
      printf("-d|-db                         Name of database file (Required)\n");
      printf("-p|-prog                       Alignment options (Required):  n (nucleotide),\n");
      printf("                                                           p (protein),\n");
      printf("                                                           trn (translated nucleotide)\n");
      printf("                                                           trnx (translated nucleotide vs protein database)\n");
      printf("-t|-top                        Number of alignments per query sequence (default 1)\n");
      printf("-f|-freqFile                   Frequency file Name\n");
      printf("-c|-heuristic                  Heuristic options: 1 (default) or 2 (See the README or paper for more information)\n");
      printf("-h|-help                       Show command line options and exit\n");
      printf("-v|-version                    Print the version and help options and exit\n");
      exit(0);
}

int input_size(FILE *f, int flag)
{
  int L = 2000, SIZE = 0, t, max = 0, total_seq = 0, temp = 0, maxsize=0 ;
  char name[L];

  while(fgets(name,L,f)!=NULL)
  {
        if (name[0] == '>'){
		total_seq++;
		t = strlen(name);
		if(t>max) max = t;
		SIZE += temp;
		if (temp >  maxsize) maxsize = temp;
		temp = 0;
                continue;
	}
        else
	{
		t = strlen(name)-1;
		if((name[t]) != '\n')
            		t++;
                temp = temp + t;
	}
  }
  SIZE += temp;
  if (temp >  maxsize) maxsize = temp;

  if (flag == 0){//DB
	TOTAL_DB_SEQ = total_seq;
        if (SIZE_SEQ<maxsize) SIZE_SEQ = maxsize;
	if (SIZE_SEQ_NAME<max) SIZE_SEQ_NAME = max;
  }
  else//query
  {
 	TOTAL_QRY_SEQ = total_seq;
        if (SIZE_SEQ<maxsize) SIZE_SEQ = maxsize;
        if (SIZE_SEQ_NAME<max) SIZE_SEQ_NAME = max;
  }
  return SIZE;
}

int main(int argc, char **argv) {
  int i;
  char queryFile[1024], refFile[1024], outputfile[1024], program[16];
  int top = 1, hypothesis = 1;
  FILE *f;

  strcpy(outputfile, "freq.txt");

  for(i=1;i<argc;i++) {
    if(!strcmp(argv[i], "-query") || !strcmp(argv[i], "-q")) {
      if(i+1 >= argc) {
	inputError("Query File name required\n");
      }
      strcpy(queryFile, argv[i+1]);
      i++;
    }
    else if(!strcmp(argv[i], "-ref") || !strcmp(argv[i], "-db") || !strcmp(argv[i], "-d")) {
      if(i+1 >= argc) {
	inputError("Database File name required\n");
      }
      strcpy(refFile, argv[i+1]);
      i++;
    }
    else if(!strcmp(argv[i], "-prog") || !strcmp(argv[i], "-p")) {
      if(i+1 >= argc) {
        inputError("Alignment option required\n");
      }
      strcpy(program, argv[i+1]);
      if (strcmp(program,"n")!=0 and strcmp(program,"p")!=0 and strcmp(program,"trn")!=0 and strcmp(program,"trnx")!=0)
	inputError("Valid alignment option required\nPlease use -h for details information\n");
      i++;
    }

    else if(!strcmp(argv[i], "-freqFile") || !strcmp(argv[i], "-f")) {
      if(i+1 >= argc) {
        inputError("Frequency File name required\n");
      }
      strcpy(outputfile, argv[i+1]);
      i++;
    }
    else if(!strcmp(argv[i], "-hypo") || !strcmp(argv[i], "-heuristic") || !strcmp(argv[i], "-c")) {
      if(i+1 >= argc) {
        inputError("Argument required\n");
      }
      sscanf(argv[i+1], "%d", &hypothesis);
      if(hypothesis <= 0 || hypothesis >=3) {
        inputError("Value of the heuristic must be either 1 (default) or 2\n");
      }
      i++;
    }
    else if(!strcmp(argv[i], "-top") || (!strcmp(argv[i], "-t")) {
      if(i+1 >= argc) {
	inputError("Argument required\n");
      }
      sscanf(argv[i+1], "%d", &top);
      if(top <= 0) {
	inputError("Value of top must be positive\n");
      }
      i++;
    }
    else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "-help"))
	    help(argv[0]);
    else if (!strcmp(argv[i], "-version") || !strcmp(argv[i], "-v"))
	    version(argv[0]);
    else {
      inputError("Invalid arguments\n");
      inputError(argv[i]);
    }
  }

  if(!queryFile[0] || !refFile[0] || !program[0]) {
    help(argv[0]);
  }

  // CHECK whether these are valid files
  unsigned int SIZEr = 0, SIZEq = 0, SIZE = 0;

  //read file:
  f = fopen(refFile,"r");
  SIZEr = input_size(f,0);
  fclose(f);
  f = fopen(queryFile,"r");
  SIZEq = input_size(f,1);
  fclose(f);

  char progBuf[1024],write_buff[1024];
  LINE_LEN = 2000;

  SIZE_SEQ++;
  SIZE_SEQ_NAME++;
  sprintf(write_buff,"%d %d %d %d %d", TOTAL_DB_SEQ, TOTAL_QRY_SEQ, LINE_LEN, SIZE_SEQ, SIZE_SEQ_NAME);

  char *app_path;
  if ((app_path = execpath(argv[0])) == NULL) {
	  fprintf(stderr, "ERROR: We can not get an application path from %s\n", argv[0]);
	  exit(-1);
  }

  if (strcmp(program,"n")==0)
  {
	SIZE = SIZEr * 2 + SIZEq + 2;
        if (SIZE >= 2000000000){
		 printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u)  * 2 + total query bp (%u)]\n",SIZE,SIZEr,SIZEq);
		inputError("");
	}

	if(hypothesis == 1)
	{
		if(top == 1)
			sprintf(progBuf, "%s/bin/search_dna_hypo1 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
		else
			sprintf(progBuf, "%s/bin/search_dna_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
	}
	else
	{
	        if(top == 1)
                        sprintf(progBuf, "%s/bin/search_dna_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
                else
                        sprintf(progBuf, "%s/bin/search_dna_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
	}
  }
  else if (strcmp(program,"p")==0)
  {
        SIZE = SIZEr + SIZEq + 2;
        if (SIZE >= 2000000000){
                          printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u) + total query bp (%u)]\n",SIZE,SIZEr,SIZEq);
                inputError("");
        }
	if(hypothesis == 1)
        {
                if(top == 1)
                        sprintf(progBuf, "%s/bin/search_pro_hypo1 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
                else
                        sprintf(progBuf, "%s/bin/search_pro_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
        }
        else
        {
                if(top == 1)
                        sprintf(progBuf, "%s/bin/search_pro_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
                else
                        sprintf(progBuf, "%s/bin/search_pro_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
        }
  }
  else if (strcmp(program,"trn")==0)
  {
        SIZE = SIZEr * 2 + SIZEq + 2;
        if (SIZE >= 2000000000) {
                          printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u)  * 2 + total query bp (%u)]\n",SIZE,SIZEr,SIZEq);
                inputError("");
        }
	if(hypothesis == 1)
        {
                if(top == 1)
                        sprintf(progBuf, "%s/bin/search_trn_hypo1 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
                else
                        sprintf(progBuf, "%s/bin/search_trn_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
        }
        else
        {
                if(top == 1)
                        sprintf(progBuf, "%s/bin/search_trn_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
                else
                        sprintf(progBuf, "%s/bin/search_trn_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
        }
  }

//////////////////
  else if (strcmp(program,"trnx")==0)
  {
        SIZE = SIZEr + SIZEq*2 + 2;
        if (SIZE >= 2000000000) {
                          printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u) + total query bp (%u) * 2]\n",SIZE,SIZEr,SIZEq);
                inputError("");
        }
        if(hypothesis == 1)
        {
                        sprintf(progBuf, "%s/bin/search_trnx_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
        }
        else
        {
		printf("Current version of Quadich supports only hypothesis I for translated nucleotide vs protein database alignmnet.\n\n");
                inputError("");
                /*if(top == 1)
                        sprintf(progBuf, "%s/bin/search_trn_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
                else
                        sprintf(progBuf, "%s/bin/search_trn_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);

	*/
        }
  }
  else{
        inputError("Please specify the correct program option\n");
      }

  printf("%s\n",progBuf);
  int returnval = system(progBuf);

  return returnval;
}

<|endoftext|>


<commit_before>/****************************************************************************
 *
 * Copyright (c) 2016 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file df_bmp280_wrapper.cpp
 * Lightweight driver to access the BMP280 of the DriverFramework.
 *
 * @author Julian Oes <julian@oes.ch>
 */

#include <px4_config.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <px4_getopt.h>
#include <errno.h>

#include <systemlib/perf_counter.h>
#include <systemlib/err.h>

#include <drivers/drv_baro.h>

#include <board_config.h>
//#include <mathlib/math/filter/LowPassFilter2p.hpp>

#include <bmp280/BMP280.hpp>
#include <DevMgr.hpp>

extern "C" { __EXPORT int df_bmp280_wrapper_main(int argc, char *argv[]); }

using namespace DriverFramework;

class DfBmp280Wrapper : public BMP280
{
public:
	DfBmp280Wrapper();
	~DfBmp280Wrapper();

	/**
	 * Start automatic measurement.
	 *
	 * @return 0 on success
	 */
	int		start();

	/**
	 * Stop automatic measurement.
	 *
	 * @return 0 on success
	 */
	int		stop();

private:
	int _publish(struct baro_sensor_data &data);

	orb_advert_t		_baro_topic;

	int			_baro_orb_class_instance;

	perf_counter_t		_baro_sample_perf;

};

DfBmp280Wrapper::DfBmp280Wrapper() :
	BMP280(BARO_DEVICE_PATH),
	_baro_topic(nullptr),
	_baro_orb_class_instance(-1),
	_baro_sample_perf(perf_alloc(PC_ELAPSED, "df_baro_read"))
{
}

DfBmp280Wrapper::~DfBmp280Wrapper()
{
	perf_free(_baro_sample_perf);
}

int DfBmp280Wrapper::start()
{
	// TODO: don't publish garbage here
	baro_report baro_report = {};
	_baro_topic = orb_advertise_multi(ORB_ID(sensor_baro), &baro_report,
					  &_baro_orb_class_instance, ORB_PRIO_DEFAULT);

	if (_baro_topic == nullptr) {
		PX4_ERR("sensor_baro advert fail");
		return -1;
	}

	/* Init device and start sensor. */
	int ret = init();

	if (ret != 0) {
		PX4_ERR("BMP280 init fail: %d", ret);
		return ret;
	}

	ret = BMP280::start();

	if (ret != 0) {
		PX4_ERR("BMP280 start fail: %d", ret);
		return ret;
	}

	return 0;
}

int DfBmp280Wrapper::stop()
{
	/* Stop sensor. */
	int ret = BMP280::stop();

	if (ret != 0) {
		PX4_ERR("BMP280 stop fail: %d", ret);
		return ret;
	}

	return 0;
}

int DfBmp280Wrapper::_publish(struct baro_sensor_data &data)
{
#if 1
	perf_begin(_baro_sample_perf);

	baro_report baro_report = {};
	baro_report.timestamp = data.last_read_time_usec;

	baro_report.pressure = data.pressure_pa;
	baro_report.temperature = data.temperature_c;

	// TODO: add this
	baro_report.altitude = -1.0f;

	// TODO: when is this ever blocked?
	if (!(m_pub_blocked)) {

		if (_baro_topic != nullptr) {
			orb_publish(ORB_ID(sensor_baro), _baro_topic, &baro_report);
		}
	}

	/* Notify anyone waiting for data. */
	DevMgr::updateNotify(*this);

	perf_end(_baro_sample_perf);
#endif

	return 0;
};

namespace df_bmp280_wrapper
{

DfBmp280Wrapper *g_dev = nullptr;

int start(/* enum Rotation rotation */);
int stop();
int info();
void usage();

int start(/*enum Rotation rotation*/)
{
	g_dev = new DfBmp280Wrapper(/*rotation*/);

	if (g_dev == nullptr) {
		PX4_ERR("failed instantiating DfBmp280Wrapper object");
		return -1;
	}

	int ret = g_dev->start();

	if (ret != 0) {
		PX4_ERR("DfBmp280Wrapper start failed");
		return ret;
	}

	// Open the IMU sensor
	DevHandle h;
	DevMgr::getHandle(BARO_DEVICE_PATH, h);

	if (!h.isValid()) {
		DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)",
			    BARO_DEVICE_PATH, h.getError());
		return -1;
	}

	DevMgr::releaseHandle(h);

	return 0;
}

int stop()
{
	if (g_dev == nullptr) {
		PX4_ERR("driver not running");
		return 1;
	}

	int ret = g_dev->stop();

	if (ret != 0) {
		PX4_ERR("driver could not be stopped");
		return ret;
	}

	delete g_dev;
	g_dev = nullptr;
	return 0;
}

/**
 * Print a little info about the driver.
 */
int
info()
{
	if (g_dev == nullptr) {
		PX4_ERR("driver not running");
		return 1;
	}

	PX4_DEBUG("state @ %p", g_dev);

	return 0;
}

void
usage()
{
	PX4_WARN("Usage: df_bmp280_wrapper 'start', 'info', 'stop'");
}

} // namespace df_bmp280_wrapper

int
df_bmp280_wrapper_main(int argc, char *argv[])
{
	int ret = 0;
	int myoptind = 1;

	if (argc <= 1) {
		df_bmp280_wrapper::usage();
		return 1;
	}

	const char *verb = argv[myoptind];

	if (!strcmp(verb, "start")) {
		ret = df_bmp280_wrapper::start();
	}

	else if (!strcmp(verb, "stop")) {
		ret = df_bmp280_wrapper::stop();
	}

	else if (!strcmp(verb, "info")) {
		ret = df_bmp280_wrapper::info();
	}

	else {
		df_bmp280_wrapper::usage();
		return 1;
	}

	return ret;
}
<commit_msg>df_bmp280_wrapper: hack to publish altitude<commit_after>/****************************************************************************
 *
 * Copyright (c) 2016 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/**
 * @file df_bmp280_wrapper.cpp
 * Lightweight driver to access the BMP280 of the DriverFramework.
 *
 * @author Julian Oes <julian@oes.ch>
 */

#include <px4_config.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <px4_getopt.h>
#include <errno.h>

#include <systemlib/perf_counter.h>
#include <systemlib/err.h>

#include <drivers/drv_baro.h>

#include <board_config.h>
//#include <mathlib/math/filter/LowPassFilter2p.hpp>

#include <bmp280/BMP280.hpp>
#include <DevMgr.hpp>

extern "C" { __EXPORT int df_bmp280_wrapper_main(int argc, char *argv[]); }

using namespace DriverFramework;

class DfBmp280Wrapper : public BMP280
{
public:
	DfBmp280Wrapper();
	~DfBmp280Wrapper();

	/**
	 * Start automatic measurement.
	 *
	 * @return 0 on success
	 */
	int		start();

	/**
	 * Stop automatic measurement.
	 *
	 * @return 0 on success
	 */
	int		stop();

private:
	int _publish(struct baro_sensor_data &data);

	orb_advert_t		_baro_topic;

	int			_baro_orb_class_instance;

	perf_counter_t		_baro_sample_perf;

};

DfBmp280Wrapper::DfBmp280Wrapper() :
	BMP280(BARO_DEVICE_PATH),
	_baro_topic(nullptr),
	_baro_orb_class_instance(-1),
	_baro_sample_perf(perf_alloc(PC_ELAPSED, "df_baro_read"))
{
}

DfBmp280Wrapper::~DfBmp280Wrapper()
{
	perf_free(_baro_sample_perf);
}

int DfBmp280Wrapper::start()
{
	// TODO: don't publish garbage here
	baro_report baro_report = {};
	_baro_topic = orb_advertise_multi(ORB_ID(sensor_baro), &baro_report,
					  &_baro_orb_class_instance, ORB_PRIO_DEFAULT);

	if (_baro_topic == nullptr) {
		PX4_ERR("sensor_baro advert fail");
		return -1;
	}

	/* Init device and start sensor. */
	int ret = init();

	if (ret != 0) {
		PX4_ERR("BMP280 init fail: %d", ret);
		return ret;
	}

	ret = BMP280::start();

	if (ret != 0) {
		PX4_ERR("BMP280 start fail: %d", ret);
		return ret;
	}

	return 0;
}

int DfBmp280Wrapper::stop()
{
	/* Stop sensor. */
	int ret = BMP280::stop();

	if (ret != 0) {
		PX4_ERR("BMP280 stop fail: %d", ret);
		return ret;
	}

	return 0;
}

int DfBmp280Wrapper::_publish(struct baro_sensor_data &data)
{
	perf_begin(_baro_sample_perf);

	baro_report baro_report = {};
	baro_report.timestamp = data.last_read_time_usec;

	baro_report.pressure = data.pressure_pa;
	baro_report.temperature = data.temperature_c;

	// TODO: verify this, it's just copied from the MS5611 driver.

	// Constant for now
	const float MSL_PRESSURE = 101325.0f;

	/* tropospheric properties (0-11km) for standard atmosphere */
	const double T1 = 15.0 + 273.15;	/* temperature at base height in Kelvin */
	const double a  = -6.5 / 1000;	/* temperature gradient in degrees per metre */
	const double g  = 9.80665;	/* gravity constant in m/s/s */
	const double R  = 287.05;	/* ideal gas constant in J/kg/K */

	/* current pressure at MSL in kPa */
	double p1 = MSL_PRESSURE / 1000.0;

	/* measured pressure in kPa */
	double p = data.pressure_pa / 1000.0;

	/*
	 * Solve:
	 *
	 *     /        -(aR / g)     \
	 *    | (p / p1)          . T1 | - T1
	 *     \                      /
	 * h = -------------------------------  + h1
	 *                   a
	 */
	baro_report.altitude = (((pow((p / p1), (-(a * R) / g))) * T1) - T1) / a;

	// TODO: when is this ever blocked?
	if (!(m_pub_blocked)) {

		if (_baro_topic != nullptr) {
			orb_publish(ORB_ID(sensor_baro), _baro_topic, &baro_report);
		}
	}

	/* Notify anyone waiting for data. */
	DevMgr::updateNotify(*this);

	perf_end(_baro_sample_perf);

	return 0;
};

namespace df_bmp280_wrapper
{

DfBmp280Wrapper *g_dev = nullptr;

int start(/* enum Rotation rotation */);
int stop();
int info();
void usage();

int start(/*enum Rotation rotation*/)
{
	g_dev = new DfBmp280Wrapper(/*rotation*/);

	if (g_dev == nullptr) {
		PX4_ERR("failed instantiating DfBmp280Wrapper object");
		return -1;
	}

	int ret = g_dev->start();

	if (ret != 0) {
		PX4_ERR("DfBmp280Wrapper start failed");
		return ret;
	}

	// Open the IMU sensor
	DevHandle h;
	DevMgr::getHandle(BARO_DEVICE_PATH, h);

	if (!h.isValid()) {
		DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)",
			    BARO_DEVICE_PATH, h.getError());
		return -1;
	}

	DevMgr::releaseHandle(h);

	return 0;
}

int stop()
{
	if (g_dev == nullptr) {
		PX4_ERR("driver not running");
		return 1;
	}

	int ret = g_dev->stop();

	if (ret != 0) {
		PX4_ERR("driver could not be stopped");
		return ret;
	}

	delete g_dev;
	g_dev = nullptr;
	return 0;
}

/**
 * Print a little info about the driver.
 */
int
info()
{
	if (g_dev == nullptr) {
		PX4_ERR("driver not running");
		return 1;
	}

	PX4_DEBUG("state @ %p", g_dev);

	return 0;
}

void
usage()
{
	PX4_WARN("Usage: df_bmp280_wrapper 'start', 'info', 'stop'");
}

} // namespace df_bmp280_wrapper

int
df_bmp280_wrapper_main(int argc, char *argv[])
{
	int ret = 0;
	int myoptind = 1;

	if (argc <= 1) {
		df_bmp280_wrapper::usage();
		return 1;
	}

	const char *verb = argv[myoptind];

	if (!strcmp(verb, "start")) {
		ret = df_bmp280_wrapper::start();
	}

	else if (!strcmp(verb, "stop")) {
		ret = df_bmp280_wrapper::stop();
	}

	else if (!strcmp(verb, "info")) {
		ret = df_bmp280_wrapper::info();
	}

	else {
		df_bmp280_wrapper::usage();
		return 1;
	}

	return ret;
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "anchormanipulator.h"

#include "formeditoritem.h"
#include "formeditorscene.h"
#include "formeditorview.h"
#include <model.h>
#include <rewritertransaction.h>

namespace QmlDesigner {

AnchorManipulator::AnchorManipulator(FormEditorView *view)
  : m_beginFormEditorItem(0),
    m_beginAnchorLine(AnchorLine::Invalid),
    m_view(view)
{
}

AnchorManipulator::~AnchorManipulator()
{
    clear();
}

void AnchorManipulator::begin(FormEditorItem *beginItem, AnchorLine::Type anchorLine)
{
   m_beginFormEditorItem = beginItem;
   m_beginAnchorLine = anchorLine;
}

static double offset(const QPointF &topLeft, const QPointF &bottomRight, AnchorLine::Type anchorLine)
{
     switch(anchorLine) {
        case AnchorLine::Top    : return topLeft.y();
        case AnchorLine::Left   : return topLeft.x();
        case AnchorLine::Bottom : return bottomRight.y();
        case AnchorLine::Right  : return bottomRight.x();
        default: break;
    }

     return 0.0;
}

void AnchorManipulator::setMargin(FormEditorItem *endItem, AnchorLine::Type endAnchorLine)
{
    QPointF beginItemTopLeft(m_beginFormEditorItem->mapToParent(m_beginFormEditorItem->qmlItemNode().instanceBoundingRect().topLeft()));
    QPointF endItemTopLeft(m_beginFormEditorItem->parentItem()->mapFromItem(endItem, endItem->qmlItemNode().instanceBoundingRect().topLeft()));

    QPointF beginItemBottomRight(m_beginFormEditorItem->mapToParent(m_beginFormEditorItem->qmlItemNode().instanceBoundingRect().bottomRight()));
    QPointF endItemBottomRight(m_beginFormEditorItem->parentItem()->mapFromItem(endItem, endItem->qmlItemNode().instanceBoundingRect().bottomRight()));

    QPointF topLeftAnchorOffset = beginItemTopLeft - endItemTopLeft;
    QPointF bottomRightAnchorOffset = endItemBottomRight - beginItemBottomRight;

    double anchorOffset = 0.0;
    if (m_beginAnchorLine & (AnchorLine::Bottom | AnchorLine::Right)) {
        anchorOffset = offset(endItemTopLeft, endItemBottomRight, endAnchorLine) -
                       offset(beginItemTopLeft, beginItemBottomRight, m_beginAnchorLine);
    } else {
        anchorOffset = offset(beginItemTopLeft, beginItemBottomRight, m_beginAnchorLine) -
                       offset(endItemTopLeft, endItemBottomRight, endAnchorLine);
    }

    m_beginFormEditorItem->qmlItemNode().anchors().setMargin(m_beginAnchorLine, anchorOffset);
}
void AnchorManipulator::addAnchor(FormEditorItem *endItem, AnchorLine::Type endAnchorLine)
{
    RewriterTransaction m_rewriterTransaction = m_view->beginRewriterTransaction();
    setMargin(endItem, endAnchorLine);

    m_beginFormEditorItem->qmlItemNode().anchors().setAnchor(m_beginAnchorLine,
                                                              endItem->qmlItemNode(),
                                                              endAnchorLine);
}

void AnchorManipulator::removeAnchor()
{
    RewriterTransaction transaction = m_view->beginRewriterTransaction();
    QmlAnchors anchors(m_beginFormEditorItem->qmlItemNode().anchors());
    if (anchors.instanceHasAnchor(m_beginAnchorLine)) {
        anchors.removeAnchor(m_beginAnchorLine);
        anchors.removeMargin(m_beginAnchorLine);
    }
}

void AnchorManipulator::clear()
{
    m_beginFormEditorItem = 0;
    m_beginAnchorLine = AnchorLine::Invalid;
}

bool AnchorManipulator::isActive() const
{
    return m_beginFormEditorItem && m_beginAnchorLine != AnchorLine::Invalid;
}

AnchorLine::Type AnchorManipulator::beginAnchorLine() const
{
    return m_beginAnchorLine;
}

bool AnchorManipulator::beginAnchorLineIsHorizontal() const
{
    return beginAnchorLine() & AnchorLine::HorizontalMask;
}
bool AnchorManipulator::beginAnchorLineIsVertical() const
{
    return beginAnchorLine() & AnchorLine::HorizontalMask;
}

FormEditorItem *AnchorManipulator::beginFormEditorItem() const
{
    return m_beginFormEditorItem;
}

} // namespace QmlDesigner
<commit_msg>Remove unused variables.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "anchormanipulator.h"

#include "formeditoritem.h"
#include "formeditorscene.h"
#include "formeditorview.h"
#include <model.h>
#include <rewritertransaction.h>

namespace QmlDesigner {

AnchorManipulator::AnchorManipulator(FormEditorView *view)
  : m_beginFormEditorItem(0),
    m_beginAnchorLine(AnchorLine::Invalid),
    m_view(view)
{
}

AnchorManipulator::~AnchorManipulator()
{
    clear();
}

void AnchorManipulator::begin(FormEditorItem *beginItem, AnchorLine::Type anchorLine)
{
   m_beginFormEditorItem = beginItem;
   m_beginAnchorLine = anchorLine;
}

static double offset(const QPointF &topLeft, const QPointF &bottomRight, AnchorLine::Type anchorLine)
{
     switch(anchorLine) {
        case AnchorLine::Top    : return topLeft.y();
        case AnchorLine::Left   : return topLeft.x();
        case AnchorLine::Bottom : return bottomRight.y();
        case AnchorLine::Right  : return bottomRight.x();
        default: break;
    }

     return 0.0;
}

void AnchorManipulator::setMargin(FormEditorItem *endItem, AnchorLine::Type endAnchorLine)
{
    QPointF beginItemTopLeft(m_beginFormEditorItem->mapToParent(m_beginFormEditorItem->qmlItemNode().instanceBoundingRect().topLeft()));
    QPointF endItemTopLeft(m_beginFormEditorItem->parentItem()->mapFromItem(endItem, endItem->qmlItemNode().instanceBoundingRect().topLeft()));

    QPointF beginItemBottomRight(m_beginFormEditorItem->mapToParent(m_beginFormEditorItem->qmlItemNode().instanceBoundingRect().bottomRight()));
    QPointF endItemBottomRight(m_beginFormEditorItem->parentItem()->mapFromItem(endItem, endItem->qmlItemNode().instanceBoundingRect().bottomRight()));

    double anchorOffset = 0.0;
    if (m_beginAnchorLine & (AnchorLine::Bottom | AnchorLine::Right)) {
        anchorOffset = offset(endItemTopLeft, endItemBottomRight, endAnchorLine) -
                       offset(beginItemTopLeft, beginItemBottomRight, m_beginAnchorLine);
    } else {
        anchorOffset = offset(beginItemTopLeft, beginItemBottomRight, m_beginAnchorLine) -
                       offset(endItemTopLeft, endItemBottomRight, endAnchorLine);
    }

    m_beginFormEditorItem->qmlItemNode().anchors().setMargin(m_beginAnchorLine, anchorOffset);
}
void AnchorManipulator::addAnchor(FormEditorItem *endItem, AnchorLine::Type endAnchorLine)
{
    RewriterTransaction m_rewriterTransaction = m_view->beginRewriterTransaction();
    setMargin(endItem, endAnchorLine);

    m_beginFormEditorItem->qmlItemNode().anchors().setAnchor(m_beginAnchorLine,
                                                              endItem->qmlItemNode(),
                                                              endAnchorLine);
}

void AnchorManipulator::removeAnchor()
{
    RewriterTransaction transaction = m_view->beginRewriterTransaction();
    QmlAnchors anchors(m_beginFormEditorItem->qmlItemNode().anchors());
    if (anchors.instanceHasAnchor(m_beginAnchorLine)) {
        anchors.removeAnchor(m_beginAnchorLine);
        anchors.removeMargin(m_beginAnchorLine);
    }
}

void AnchorManipulator::clear()
{
    m_beginFormEditorItem = 0;
    m_beginAnchorLine = AnchorLine::Invalid;
}

bool AnchorManipulator::isActive() const
{
    return m_beginFormEditorItem && m_beginAnchorLine != AnchorLine::Invalid;
}

AnchorLine::Type AnchorManipulator::beginAnchorLine() const
{
    return m_beginAnchorLine;
}

bool AnchorManipulator::beginAnchorLineIsHorizontal() const
{
    return beginAnchorLine() & AnchorLine::HorizontalMask;
}
bool AnchorManipulator::beginAnchorLineIsVertical() const
{
    return beginAnchorLine() & AnchorLine::HorizontalMask;
}

FormEditorItem *AnchorManipulator::beginFormEditorItem() const
{
    return m_beginFormEditorItem;
}

} // namespace QmlDesigner
<|endoftext|>