<commit_before>/*===- Cloud.cpp - libSimulation -==============================================
*
*                                  DEMON
*
* This file is distributed under the BSD Open Source License. See LICENSE.TXT
* for details.
*
*===-----------------------------------------------------------------------===*/

#include "Cloud.h"
#include <cmath>
#include <sstream>

using namespace std;

Cloud::Cloud(cloud_index numPar, double sizeOfCloud) : n(numPar), cloudSize(sizeOfCloud),
k1(new double[n]), k2(new double[n]), k3(new double[n]), k4(new double[n]),
l1(new double[n]), l2(new double[n]), l3(new double[n]), l4(new double[n]),
m1(new double[n]), m2(new double[n]), m3(new double[n]), m4(new double[n]),
n1(new double[n]), n2(new double[n]), n3(new double[n]), n4(new double[n]),
x(new double[n]), y(new double[n]), Vx(new double[n]), Vy(new double[n]),
charge(new double[n]), mass(new double[n]),
forceX(new double[n]), forceY(new double[n]),
xCache(new __m128d[n/2]), yCache(new __m128d[n/2]),
VxCache(new __m128d[n/2]), VyCache(new __m128d[n/2]) {}

Cloud::~Cloud()
{
	delete[] k1; delete[] k2; delete[] k3; delete[] k4;
	delete[] l1; delete[] l2; delete[] l3; delete[] l4;
	delete[] m1; delete[] m2; delete[] m3; delete[] m4;
	delete[] n1; delete[] n2; delete[] n3; delete[] n4;
	delete[] x; delete[] y; delete[] Vx; delete[] Vy;
	delete[] charge; delete[] mass;
	delete[] forceX; delete[] forceY;
	delete[] xCache; delete[] yCache;
	delete[] VxCache; delete[] VyCache;
}

inline void Cloud::setPosition(const cloud_index index, const double xVal, const double yVal)
{
	x[index] = xVal;
	y[index] = yVal;
}

inline void Cloud::setVelocity(const cloud_index index)
{
	Vx[index] = 0.0;
	Vy[index] = 0.0;
}

inline void Cloud::setCharge(const cloud_index index)
{
	charge[index] = (rand()%201 + 5900)*1.6E-19;
}

inline void Cloud::setMass(const cloud_index index)
{
	const double radius = 1.45E-6;
	const double particleDensity = 2200.0;
	mass[index] = (4.0/3.0)*M_PI*radius*radius*radius*particleDensity;
}

Cloud * const Cloud::initializeGrid(const cloud_index numParticles, const double cloudSize)
{
	Cloud * const cloud = new Cloud(numParticles, cloudSize);

	const double sqrtNumPar = floor(sqrt(numParticles));
	const double gridUnit = 2.0*cloudSize/sqrtNumPar; // number of particles per row/column
	double tempPosX = cloudSize; // position of first particle
	double tempPosY = cloudSize;

	// seed rand function with time(NULL):
	srand((int)time(NULL)); // needed for Cloud::setCharge

	// initialize dust cloud:
	for (cloud_index i = 0; i < numParticles; i++)
	{
		cloud->setPosition(i, tempPosX, tempPosY);
		cloud->setVelocity(i);
		cloud->setCharge(i);
		cloud->setMass(i);

		tempPosX -= gridUnit;
		if (tempPosX <= -cloudSize) // end of row
		{
			tempPosX = cloudSize; // reset
			tempPosY -= gridUnit; // move to next row
		}
	}

	return cloud;
}

Cloud * const Cloud::initializeFromFile(fitsfile * const file, int * const error, double * const currentTime)
{
	int *anyNull = NULL;
	long numParticles;
	long numTimeSteps;

	// move to CLOUD HDU:
	if (!*error)
		fits_movnam_hdu(file, BINARY_TBL, const_cast<char *> ("CLOUD"), 0, error);

	// get number of particles:
	if (!*error)
		fits_get_num_rows(file, &numParticles, error);

	// create cloud:
	Cloud * const cloud = new Cloud((cloud_index)numParticles, 0.0); // cloudSize not used in this case, so set to zero

	// read mass and charge information:
	if (!*error)
	{
		// file, column #, starting row, first element, num elements, mass array, pointless pointer, error
		fits_read_col_dbl(file, 1, 1, 1, numParticles, 0.0, cloud->charge, anyNull, error);
		fits_read_col_dbl(file, 2, 1, 1, numParticles, 0.0, cloud->mass, anyNull, error);
	}

	// move to TIME_STEP HDU:
	if (!*error)
		fits_movnam_hdu(file, BINARY_TBL, const_cast<char *> ("TIME_STEP"), 0, error);

	// get number of time steps:
	if (!*error)
		fits_get_num_rows(file, &numTimeSteps, error);

	if (!*error)
	{
		if (currentTime)
			fits_read_col_dbl(file, 1, numTimeSteps, 1, 1, 0.0, currentTime, anyNull, error);

		fits_read_col_dbl(file, 2, numTimeSteps, 1, numParticles, 0.0, cloud->x, anyNull, error);
		fits_read_col_dbl(file, 3, numTimeSteps, 1, numParticles, 0.0, cloud->y, anyNull, error);
		fits_read_col_dbl(file, 4, numTimeSteps, 1, numParticles, 0.0, cloud->Vx, anyNull, error);
		fits_read_col_dbl(file, 5, numTimeSteps, 1, numParticles, 0.0, cloud->Vy, anyNull, error);
	}

	return cloud;
}

void Cloud::writeCloudSetup(fitsfile * const file, int * const error) const
{
	// format number of elements of type double as string, e.g. 1024D
	stringstream numStream;
	numStream << n << "D";
	const string numString = numStream.str();

	char *ttypeCloud[] = {const_cast<char *> ("CHARGE"), const_cast<char *> ("MASS")};
	char *tformCloud[] = {const_cast<char *> ("D"), const_cast<char *> ("D")};
	char *tunitCloud[] = {const_cast<char *> ("C"), const_cast<char *> ("kg")};

	char *ttypeRun[] = {const_cast<char *> ("TIME"),
		const_cast<char *> ("X_POSITION"), const_cast<char *> ("Y_POSITION"),
		const_cast<char *> ("X_VELOCITY"), const_cast<char *> ("Y_VELOCITY")};
	char *tformRun[] = {const_cast<char *> ("D"),
		const_cast<char *> (numString.c_str()), const_cast<char *> (numString.c_str()),
		const_cast<char *> (numString.c_str()), const_cast<char *> (numString.c_str())};
	char *tunitRun[] = {const_cast<char *> ("s"),
		const_cast<char *> ("m"), const_cast<char *> ("m"),
		const_cast<char *> ("m/s"), const_cast<char *> ("m/s")};

	// write mass and charge:
	if (!*error)
		// file, storage type, num rows, num columns, ...
		fits_create_tbl(file, BINARY_TBL, n, 2, ttypeCloud, tformCloud, tunitCloud, "CLOUD", error);
	if (!*error)
	{
		// file, column #, starting row, first element, num elements, mass array, error
		fits_write_col_dbl(file, 1, 1, 1, n, charge, error);
		fits_write_col_dbl(file, 2, 1, 1, n, mass, error);
	}

	// write position and velocity:
	if (!*error)
		fits_create_tbl(file, BINARY_TBL, 0, 5, ttypeRun, tformRun, tunitRun, "TIME_STEP", error);
		// n.b. num rows automatically incremented.
		// Increment from 0 as opposed to preallocating to ensure
		// proper output in the event of program interruption.
	if (!*error)
	{
		double time = 0.0;
		fits_write_col_dbl(file, 1, 1, 1, 1, &time, error);
		fits_write_col_dbl(file, 2, 1, 1, n, x, error);
		fits_write_col_dbl(file, 3, 1, 1, n, y, error);
		fits_write_col_dbl(file, 4, 1, 1, n, Vx, error);
		fits_write_col_dbl(file, 5, 1, 1, n, Vy, error);
	}

	// write buffer, close file, reopen at same point:
	fits_flush_file(file, error);
}

void Cloud::writeTimeStep(fitsfile * const file, int * const error, double currentTime) const
{
	if (!*error)
	{
		long numRows = 0;
		fits_get_num_rows(file, &numRows, error);
		fits_write_col_dbl(file, 1, ++numRows, 1, 1, &currentTime, error);
		fits_write_col_dbl(file, 2, numRows, 1, n, x, error);
		fits_write_col_dbl(file, 3, numRows, 1, n, y, error);
		fits_write_col_dbl(file, 4, numRows, 1, n, Vx, error);
		fits_write_col_dbl(file, 5, numRows, 1, n, Vy, error);
	}

	// write buffer, close file, reopen at same point:
	fits_flush_file(file, error);
}

// 4th order Runge-Kutta subsetp helper methods.

// X position helper functions -------------------------------------------------
const __m128d Cloud::getx1_pd(const cloud_index i) const
{
	// x
	return _mm_load_pd(x + i);
}

const __m128d Cloud::getx2_pd(const cloud_index i) const
{
	// x + l1/2
	return xCache[i/2];
}

const __m128d Cloud::getx3_pd(const cloud_index i) const
{
	// x + l2/2
	return xCache[i/2];
}

const __m128d Cloud::getx4_pd(const cloud_index i) const
{
	// x + l3
	return xCache[i/2];
}

const __m128d Cloud::getx1r_pd(const cloud_index i) const
{
	return _mm_loadr_pd(x + i);
}

const __m128d Cloud::getx2r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(xCache[j], xCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::getx3r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(xCache[j], xCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::getx4r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(xCache[j], xCache[j], _MM_SHUFFLE2(0, 1));
}

// Y position helper functions -------------------------------------------------
const __m128d Cloud::gety1_pd(const cloud_index i) const
{
	// y
	return _mm_load_pd(y + i);
}

const __m128d Cloud::gety2_pd(const cloud_index i) const
{
	// y + n1/2
	return yCache[i/2];
}

const __m128d Cloud::gety3_pd(const cloud_index i) const
{
	// y + n2/2
	return yCache[i/2];
}

const __m128d Cloud::gety4_pd(const cloud_index i) const
{
	// y + n3
	return yCache[i/2];
}

const __m128d Cloud::gety1r_pd(const cloud_index i) const
{
	return _mm_loadr_pd(y + i);
}

const __m128d Cloud::gety2r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(yCache[j], yCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::gety3r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(yCache[j], yCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::gety4r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(yCache[j], yCache[j], _MM_SHUFFLE2(0, 1));
}

// Vx position helper functions ------------------------------------------------
const __m128d Cloud::getVx1_pd(const cloud_index i) const
{
	// Vx
	return _mm_load_pd(Vx + i);
}

const __m128d Cloud::getVx2_pd(const cloud_index i) const
{
	// Vx + k1/2
	return VxCache[i/2];
}

const __m128d Cloud::getVx3_pd(const cloud_index i) const
{
	// Vx + k2/2
	return VxCache[i/2];
}

const __m128d Cloud::getVx4_pd(const cloud_index i) const
{
	// Vx + k3
	return VxCache[i/2];
}

// Vy position helper functions ------------------------------------------------
const __m128d Cloud::getVy1_pd(const cloud_index i) const
{
	// Vy
	return _mm_load_pd(Vy + i);
}

const __m128d Cloud::getVy2_pd(const cloud_index i) const
{
	// Vy + m1/2
	return VyCache[i/2];
}

const __m128d Cloud::getVy3_pd(const cloud_index i) const
{
	// Vy + m2/2
	return VyCache[i/2];
}

const __m128d Cloud::getVy4_pd(const cloud_index i) const
{
	// Vy + m3
	return VyCache[i/2];
}
<commit_msg>Initialize uninitalized variable to avoid error when compiling with -Wuninitialized.<commit_after>/*===- Cloud.cpp - libSimulation -==============================================
*
*                                  DEMON
*
* This file is distributed under the BSD Open Source License. See LICENSE.TXT
* for details.
*
*===-----------------------------------------------------------------------===*/

#include "Cloud.h"
#include <cmath>
#include <sstream>

using namespace std;

Cloud::Cloud(cloud_index numPar, double sizeOfCloud) : n(numPar), cloudSize(sizeOfCloud),
k1(new double[n]), k2(new double[n]), k3(new double[n]), k4(new double[n]),
l1(new double[n]), l2(new double[n]), l3(new double[n]), l4(new double[n]),
m1(new double[n]), m2(new double[n]), m3(new double[n]), m4(new double[n]),
n1(new double[n]), n2(new double[n]), n3(new double[n]), n4(new double[n]),
x(new double[n]), y(new double[n]), Vx(new double[n]), Vy(new double[n]),
charge(new double[n]), mass(new double[n]),
forceX(new double[n]), forceY(new double[n]),
xCache(new __m128d[n/2]), yCache(new __m128d[n/2]),
VxCache(new __m128d[n/2]), VyCache(new __m128d[n/2]) {}

Cloud::~Cloud()
{
	delete[] k1; delete[] k2; delete[] k3; delete[] k4;
	delete[] l1; delete[] l2; delete[] l3; delete[] l4;
	delete[] m1; delete[] m2; delete[] m3; delete[] m4;
	delete[] n1; delete[] n2; delete[] n3; delete[] n4;
	delete[] x; delete[] y; delete[] Vx; delete[] Vy;
	delete[] charge; delete[] mass;
	delete[] forceX; delete[] forceY;
	delete[] xCache; delete[] yCache;
	delete[] VxCache; delete[] VyCache;
}

inline void Cloud::setPosition(const cloud_index index, const double xVal, const double yVal)
{
	x[index] = xVal;
	y[index] = yVal;
}

inline void Cloud::setVelocity(const cloud_index index)
{
	Vx[index] = 0.0;
	Vy[index] = 0.0;
}

inline void Cloud::setCharge(const cloud_index index)
{
	charge[index] = (rand()%201 + 5900)*1.6E-19;
}

inline void Cloud::setMass(const cloud_index index)
{
	const double radius = 1.45E-6;
	const double particleDensity = 2200.0;
	mass[index] = (4.0/3.0)*M_PI*radius*radius*radius*particleDensity;
}

Cloud * const Cloud::initializeGrid(const cloud_index numParticles, const double cloudSize)
{
	Cloud * const cloud = new Cloud(numParticles, cloudSize);

	const double sqrtNumPar = floor(sqrt(numParticles));
	const double gridUnit = 2.0*cloudSize/sqrtNumPar; // number of particles per row/column
	double tempPosX = cloudSize; // position of first particle
	double tempPosY = cloudSize;

	// seed rand function with time(NULL):
	srand((int)time(NULL)); // needed for Cloud::setCharge

	// initialize dust cloud:
	for (cloud_index i = 0; i < numParticles; i++)
	{
		cloud->setPosition(i, tempPosX, tempPosY);
		cloud->setVelocity(i);
		cloud->setCharge(i);
		cloud->setMass(i);

		tempPosX -= gridUnit;
		if (tempPosX <= -cloudSize) // end of row
		{
			tempPosX = cloudSize; // reset
			tempPosY -= gridUnit; // move to next row
		}
	}

	return cloud;
}

Cloud * const Cloud::initializeFromFile(fitsfile * const file, int * const error, double * const currentTime)
{
	int *anyNull = NULL;
	long numParticles = 0;
	long numTimeSteps = 0;

	// move to CLOUD HDU:
	if (!*error)
		fits_movnam_hdu(file, BINARY_TBL, const_cast<char *> ("CLOUD"), 0, error);

	// get number of particles:
	if (!*error)
		fits_get_num_rows(file, &numParticles, error);

	// create cloud:
	Cloud * const cloud = new Cloud((cloud_index)numParticles, 0.0); // cloudSize not used in this case, so set to zero

	// read mass and charge information:
	if (!*error)
	{
		// file, column #, starting row, first element, num elements, mass array, pointless pointer, error
		fits_read_col_dbl(file, 1, 1, 1, numParticles, 0.0, cloud->charge, anyNull, error);
		fits_read_col_dbl(file, 2, 1, 1, numParticles, 0.0, cloud->mass, anyNull, error);
	}

	// move to TIME_STEP HDU:
	if (!*error)
		fits_movnam_hdu(file, BINARY_TBL, const_cast<char *> ("TIME_STEP"), 0, error);

	// get number of time steps:
	if (!*error)
		fits_get_num_rows(file, &numTimeSteps, error);

	if (!*error)
	{
		if (currentTime)
			fits_read_col_dbl(file, 1, numTimeSteps, 1, 1, 0.0, currentTime, anyNull, error);

		fits_read_col_dbl(file, 2, numTimeSteps, 1, numParticles, 0.0, cloud->x, anyNull, error);
		fits_read_col_dbl(file, 3, numTimeSteps, 1, numParticles, 0.0, cloud->y, anyNull, error);
		fits_read_col_dbl(file, 4, numTimeSteps, 1, numParticles, 0.0, cloud->Vx, anyNull, error);
		fits_read_col_dbl(file, 5, numTimeSteps, 1, numParticles, 0.0, cloud->Vy, anyNull, error);
	}

	return cloud;
}

void Cloud::writeCloudSetup(fitsfile * const file, int * const error) const
{
	// format number of elements of type double as string, e.g. 1024D
	stringstream numStream;
	numStream << n << "D";
	const string numString = numStream.str();

	char *ttypeCloud[] = {const_cast<char *> ("CHARGE"), const_cast<char *> ("MASS")};
	char *tformCloud[] = {const_cast<char *> ("D"), const_cast<char *> ("D")};
	char *tunitCloud[] = {const_cast<char *> ("C"), const_cast<char *> ("kg")};

	char *ttypeRun[] = {const_cast<char *> ("TIME"),
		const_cast<char *> ("X_POSITION"), const_cast<char *> ("Y_POSITION"),
		const_cast<char *> ("X_VELOCITY"), const_cast<char *> ("Y_VELOCITY")};
	char *tformRun[] = {const_cast<char *> ("D"),
		const_cast<char *> (numString.c_str()), const_cast<char *> (numString.c_str()),
		const_cast<char *> (numString.c_str()), const_cast<char *> (numString.c_str())};
	char *tunitRun[] = {const_cast<char *> ("s"),
		const_cast<char *> ("m"), const_cast<char *> ("m"),
		const_cast<char *> ("m/s"), const_cast<char *> ("m/s")};

	// write mass and charge:
	if (!*error)
		// file, storage type, num rows, num columns, ...
		fits_create_tbl(file, BINARY_TBL, n, 2, ttypeCloud, tformCloud, tunitCloud, "CLOUD", error);
	if (!*error)
	{
		// file, column #, starting row, first element, num elements, mass array, error
		fits_write_col_dbl(file, 1, 1, 1, n, charge, error);
		fits_write_col_dbl(file, 2, 1, 1, n, mass, error);
	}

	// write position and velocity:
	if (!*error)
		fits_create_tbl(file, BINARY_TBL, 0, 5, ttypeRun, tformRun, tunitRun, "TIME_STEP", error);
		// n.b. num rows automatically incremented.
		// Increment from 0 as opposed to preallocating to ensure
		// proper output in the event of program interruption.
	if (!*error)
	{
		double time = 0.0;
		fits_write_col_dbl(file, 1, 1, 1, 1, &time, error);
		fits_write_col_dbl(file, 2, 1, 1, n, x, error);
		fits_write_col_dbl(file, 3, 1, 1, n, y, error);
		fits_write_col_dbl(file, 4, 1, 1, n, Vx, error);
		fits_write_col_dbl(file, 5, 1, 1, n, Vy, error);
	}

	// write buffer, close file, reopen at same point:
	fits_flush_file(file, error);
}

void Cloud::writeTimeStep(fitsfile * const file, int * const error, double currentTime) const
{
	if (!*error)
	{
		long numRows = 0;
		fits_get_num_rows(file, &numRows, error);
		fits_write_col_dbl(file, 1, ++numRows, 1, 1, &currentTime, error);
		fits_write_col_dbl(file, 2, numRows, 1, n, x, error);
		fits_write_col_dbl(file, 3, numRows, 1, n, y, error);
		fits_write_col_dbl(file, 4, numRows, 1, n, Vx, error);
		fits_write_col_dbl(file, 5, numRows, 1, n, Vy, error);
	}

	// write buffer, close file, reopen at same point:
	fits_flush_file(file, error);
}

// 4th order Runge-Kutta subsetp helper methods.

// X position helper functions -------------------------------------------------
const __m128d Cloud::getx1_pd(const cloud_index i) const
{
	// x
	return _mm_load_pd(x + i);
}

const __m128d Cloud::getx2_pd(const cloud_index i) const
{
	// x + l1/2
	return xCache[i/2];
}

const __m128d Cloud::getx3_pd(const cloud_index i) const
{
	// x + l2/2
	return xCache[i/2];
}

const __m128d Cloud::getx4_pd(const cloud_index i) const
{
	// x + l3
	return xCache[i/2];
}

const __m128d Cloud::getx1r_pd(const cloud_index i) const
{
	return _mm_loadr_pd(x + i);
}

const __m128d Cloud::getx2r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(xCache[j], xCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::getx3r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(xCache[j], xCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::getx4r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(xCache[j], xCache[j], _MM_SHUFFLE2(0, 1));
}

// Y position helper functions -------------------------------------------------
const __m128d Cloud::gety1_pd(const cloud_index i) const
{
	// y
	return _mm_load_pd(y + i);
}

const __m128d Cloud::gety2_pd(const cloud_index i) const
{
	// y + n1/2
	return yCache[i/2];
}

const __m128d Cloud::gety3_pd(const cloud_index i) const
{
	// y + n2/2
	return yCache[i/2];
}

const __m128d Cloud::gety4_pd(const cloud_index i) const
{
	// y + n3
	return yCache[i/2];
}

const __m128d Cloud::gety1r_pd(const cloud_index i) const
{
	return _mm_loadr_pd(y + i);
}

const __m128d Cloud::gety2r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(yCache[j], yCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::gety3r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(yCache[j], yCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::gety4r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(yCache[j], yCache[j], _MM_SHUFFLE2(0, 1));
}

// Vx position helper functions ------------------------------------------------
const __m128d Cloud::getVx1_pd(const cloud_index i) const
{
	// Vx
	return _mm_load_pd(Vx + i);
}

const __m128d Cloud::getVx2_pd(const cloud_index i) const
{
	// Vx + k1/2
	return VxCache[i/2];
}

const __m128d Cloud::getVx3_pd(const cloud_index i) const
{
	// Vx + k2/2
	return VxCache[i/2];
}

const __m128d Cloud::getVx4_pd(const cloud_index i) const
{
	// Vx + k3
	return VxCache[i/2];
}

// Vy position helper functions ------------------------------------------------
const __m128d Cloud::getVy1_pd(const cloud_index i) const
{
	// Vy
	return _mm_load_pd(Vy + i);
}

const __m128d Cloud::getVy2_pd(const cloud_index i) const
{
	// Vy + m1/2
	return VyCache[i/2];
}

const __m128d Cloud::getVy3_pd(const cloud_index i) const
{
	// Vy + m2/2
	return VyCache[i/2];
}

const __m128d Cloud::getVy4_pd(const cloud_index i) const
{
	// Vy + m3
	return VyCache[i/2];
}
<|endoftext|>


<commit_before>/*===- Cloud.cpp - libSimulation -==============================================
*
*                                  DEMON
*
* This file is distributed under the BSD Open Source License. See LICENSE.TXT
* for details.
*
*===-----------------------------------------------------------------------===*/

#include "Cloud.h"
#include <cmath>
#include <sstream>

using namespace std;

const double Cloud::interParticleSpacing = 0.0003;

Cloud::Cloud(cloud_index numPar) : n(numPar),
k1(new double[n]), k2(new double[n]), k3(new double[n]), k4(new double[n]),
l1(new double[n]), l2(new double[n]), l3(new double[n]), l4(new double[n]),
m1(new double[n]), m2(new double[n]), m3(new double[n]), m4(new double[n]),
n1(new double[n]), n2(new double[n]), n3(new double[n]), n4(new double[n]),
x(new double[n]), y(new double[n]), Vx(new double[n]), Vy(new double[n]),
charge(new double[n]), mass(new double[n]),
forceX(new double[n]), forceY(new double[n]),
xCache(new __m128d[n/2]), yCache(new __m128d[n/2]),
VxCache(new __m128d[n/2]), VyCache(new __m128d[n/2]) {}

Cloud::~Cloud()
{
	delete[] k1; delete[] k2; delete[] k3; delete[] k4;
	delete[] l1; delete[] l2; delete[] l3; delete[] l4;
	delete[] m1; delete[] m2; delete[] m3; delete[] m4;
	delete[] n1; delete[] n2; delete[] n3; delete[] n4;
	delete[] x; delete[] y; delete[] Vx; delete[] Vy;
	delete[] charge; delete[] mass;
	delete[] forceX; delete[] forceY;
	delete[] xCache; delete[] yCache;
	delete[] VxCache; delete[] VyCache;
}

inline void Cloud::setPosition(const cloud_index index, const double xVal, const double yVal)
{
	x[index] = xVal;
	y[index] = yVal;
}

inline void Cloud::setVelocity(const cloud_index index)
{
	Vx[index] = 0.0;
	Vy[index] = 0.0;
}

inline void Cloud::setCharge()
{
	srand((int)time(NULL));
	for (cloud_index i = 0; i < n; i++)
		charge[i] = (rand()%201 + 5900)*1.6E-19;
}

inline void Cloud::setMass()
{
	const double radius = 1.45E-6;
	const double particleDensity = 2200.0;
	const double particleMass = (4.0/3.0)*M_PI*radius*radius*radius*particleDensity;
	for (cloud_index i = 0; i < n; i++)
		mass[i] = particleMass;
}

Cloud * const Cloud::initializeGrid(const cloud_index numParticles)
{
	Cloud * const cloud = new Cloud(numParticles);

	const cloud_index sqrtNumPar = (cloud_index)floor(sqrt(numParticles));

	// For even numbers of partciles on a row center the row over the origin.
	const double cloudHalfSize = (double)sqrtNumPar/2.0*interParticleSpacing
		- ((sqrtNumPar%2) ? interParticleSpacing/2.0 : 0.0); // cloud halfwidth.

	cloud->setCharge();
	cloud->setMass();
	for (cloud_index i = 0, j = 0; i < numParticles; i++, j++)
	{
		cloud->setPosition(i,
			cloudHalfSize - (double)(i%sqrtNumPar)*interParticleSpacing,
			cloudHalfSize - (double)(i/sqrtNumPar)*interParticleSpacing);
		cloud->setVelocity(i);
	}

	return cloud;
}

Cloud * const Cloud::initializeFromFile(fitsfile * const file, int * const error, double * const currentTime)
{
	int *anyNull = NULL;
	long numParticles = 0;
	long numTimeSteps = 0;

	// move to CLOUD HDU:
	if (!*error)
		fits_movnam_hdu(file, BINARY_TBL, const_cast<char *> ("CLOUD"), 0, error);

	// get number of particles:
	if (!*error)
		fits_get_num_rows(file, &numParticles, error);

	// create cloud:
	Cloud * const cloud = new Cloud((cloud_index)numParticles); // cloudSize not used in this case, so set to zero

	// read mass and charge information:
	if (!*error)
	{
		// file, column #, starting row, first element, num elements, mass array, pointless pointer, error
		fits_read_col_dbl(file, 1, 1, 1, numParticles, 0.0, cloud->charge, anyNull, error);
		fits_read_col_dbl(file, 2, 1, 1, numParticles, 0.0, cloud->mass, anyNull, error);
	}

	// move to TIME_STEP HDU:
	if (!*error)
		fits_movnam_hdu(file, BINARY_TBL, const_cast<char *> ("TIME_STEP"), 0, error);

	// get number of time steps:
	if (!*error)
		fits_get_num_rows(file, &numTimeSteps, error);

	if (!*error)
	{
		if (currentTime)
			fits_read_col_dbl(file, 1, numTimeSteps, 1, 1, 0.0, currentTime, anyNull, error);

		fits_read_col_dbl(file, 2, numTimeSteps, 1, numParticles, 0.0, cloud->x, anyNull, error);
		fits_read_col_dbl(file, 3, numTimeSteps, 1, numParticles, 0.0, cloud->y, anyNull, error);
		fits_read_col_dbl(file, 4, numTimeSteps, 1, numParticles, 0.0, cloud->Vx, anyNull, error);
		fits_read_col_dbl(file, 5, numTimeSteps, 1, numParticles, 0.0, cloud->Vy, anyNull, error);
	}

	return cloud;
}

void Cloud::writeCloudSetup(fitsfile * const file, int * const error) const
{
	// format number of elements of type double as string, e.g. 1024D
	stringstream numStream;
	numStream << n << "D";
	const string numString = numStream.str();

	char *ttypeCloud[] = {const_cast<char *> ("CHARGE"), const_cast<char *> ("MASS")};
	char *tformCloud[] = {const_cast<char *> ("D"), const_cast<char *> ("D")};
	char *tunitCloud[] = {const_cast<char *> ("C"), const_cast<char *> ("kg")};

	char *ttypeRun[] = {const_cast<char *> ("TIME"),
		const_cast<char *> ("X_POSITION"), const_cast<char *> ("Y_POSITION"),
		const_cast<char *> ("X_VELOCITY"), const_cast<char *> ("Y_VELOCITY")};
	char *tformRun[] = {const_cast<char *> ("D"),
		const_cast<char *> (numString.c_str()), const_cast<char *> (numString.c_str()),
		const_cast<char *> (numString.c_str()), const_cast<char *> (numString.c_str())};
	char *tunitRun[] = {const_cast<char *> ("s"),
		const_cast<char *> ("m"), const_cast<char *> ("m"),
		const_cast<char *> ("m/s"), const_cast<char *> ("m/s")};

	// write mass and charge:
	if (!*error)
		// file, storage type, num rows, num columns, ...
		fits_create_tbl(file, BINARY_TBL, n, 2, ttypeCloud, tformCloud, tunitCloud, "CLOUD", error);
	if (!*error)
	{
		// file, column #, starting row, first element, num elements, mass array, error
		fits_write_col_dbl(file, 1, 1, 1, n, charge, error);
		fits_write_col_dbl(file, 2, 1, 1, n, mass, error);
	}

	// write position and velocity:
	if (!*error)
		fits_create_tbl(file, BINARY_TBL, 0, 5, ttypeRun, tformRun, tunitRun, "TIME_STEP", error);
		// n.b. num rows automatically incremented.
		// Increment from 0 as opposed to preallocating to ensure
		// proper output in the event of program interruption.
	if (!*error)
	{
		double time = 0.0;
		fits_write_col_dbl(file, 1, 1, 1, 1, &time, error);
		fits_write_col_dbl(file, 2, 1, 1, n, x, error);
		fits_write_col_dbl(file, 3, 1, 1, n, y, error);
		fits_write_col_dbl(file, 4, 1, 1, n, Vx, error);
		fits_write_col_dbl(file, 5, 1, 1, n, Vy, error);
	}

	// write buffer, close file, reopen at same point:
	fits_flush_file(file, error);
}

void Cloud::writeTimeStep(fitsfile * const file, int * const error, double currentTime) const
{
	if (!*error)
	{
		long numRows = 0;
		fits_get_num_rows(file, &numRows, error);
		fits_write_col_dbl(file, 1, ++numRows, 1, 1, &currentTime, error);
		fits_write_col_dbl(file, 2, numRows, 1, n, x, error);
		fits_write_col_dbl(file, 3, numRows, 1, n, y, error);
		fits_write_col_dbl(file, 4, numRows, 1, n, Vx, error);
		fits_write_col_dbl(file, 5, numRows, 1, n, Vy, error);
	}

	// write buffer, close file, reopen at same point:
	fits_flush_file(file, error);
}

// 4th order Runge-Kutta subsetp helper methods.

// X position helper functions -------------------------------------------------
const __m128d Cloud::getx1_pd(const cloud_index i) const
{
	// x
	return _mm_load_pd(x + i);
}

const __m128d Cloud::getx2_pd(const cloud_index i) const
{
	// x + l1/2
	return xCache[i/2];
}

const __m128d Cloud::getx3_pd(const cloud_index i) const
{
	// x + l2/2
	return xCache[i/2];
}

const __m128d Cloud::getx4_pd(const cloud_index i) const
{
	// x + l3
	return xCache[i/2];
}

const __m128d Cloud::getx1r_pd(const cloud_index i) const
{
	return _mm_loadr_pd(x + i);
}

const __m128d Cloud::getx2r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(xCache[j], xCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::getx3r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(xCache[j], xCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::getx4r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(xCache[j], xCache[j], _MM_SHUFFLE2(0, 1));
}

// Y position helper functions -------------------------------------------------
const __m128d Cloud::gety1_pd(const cloud_index i) const
{
	// y
	return _mm_load_pd(y + i);
}

const __m128d Cloud::gety2_pd(const cloud_index i) const
{
	// y + n1/2
	return yCache[i/2];
}

const __m128d Cloud::gety3_pd(const cloud_index i) const
{
	// y + n2/2
	return yCache[i/2];
}

const __m128d Cloud::gety4_pd(const cloud_index i) const
{
	// y + n3
	return yCache[i/2];
}

const __m128d Cloud::gety1r_pd(const cloud_index i) const
{
	return _mm_loadr_pd(y + i);
}

const __m128d Cloud::gety2r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(yCache[j], yCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::gety3r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(yCache[j], yCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::gety4r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(yCache[j], yCache[j], _MM_SHUFFLE2(0, 1));
}

// Vx position helper functions ------------------------------------------------
const __m128d Cloud::getVx1_pd(const cloud_index i) const
{
	// Vx
	return _mm_load_pd(Vx + i);
}

const __m128d Cloud::getVx2_pd(const cloud_index i) const
{
	// Vx + k1/2
	return VxCache[i/2];
}

const __m128d Cloud::getVx3_pd(const cloud_index i) const
{
	// Vx + k2/2
	return VxCache[i/2];
}

const __m128d Cloud::getVx4_pd(const cloud_index i) const
{
	// Vx + k3
	return VxCache[i/2];
}

// Vy position helper functions ------------------------------------------------
const __m128d Cloud::getVy1_pd(const cloud_index i) const
{
	// Vy
	return _mm_load_pd(Vy + i);
}

const __m128d Cloud::getVy2_pd(const cloud_index i) const
{
	// Vy + m1/2
	return VyCache[i/2];
}

const __m128d Cloud::getVy3_pd(const cloud_index i) const
{
	// Vy + m2/2
	return VyCache[i/2];
}

const __m128d Cloud::getVy4_pd(const cloud_index i) const
{
	// Vy + m3
	return VyCache[i/2];
}
<commit_msg>Remove unused j index.<commit_after>/*===- Cloud.cpp - libSimulation -==============================================
*
*                                  DEMON
*
* This file is distributed under the BSD Open Source License. See LICENSE.TXT
* for details.
*
*===-----------------------------------------------------------------------===*/

#include "Cloud.h"
#include <cmath>
#include <sstream>

using namespace std;

const double Cloud::interParticleSpacing = 0.0003;

Cloud::Cloud(cloud_index numPar) : n(numPar),
k1(new double[n]), k2(new double[n]), k3(new double[n]), k4(new double[n]),
l1(new double[n]), l2(new double[n]), l3(new double[n]), l4(new double[n]),
m1(new double[n]), m2(new double[n]), m3(new double[n]), m4(new double[n]),
n1(new double[n]), n2(new double[n]), n3(new double[n]), n4(new double[n]),
x(new double[n]), y(new double[n]), Vx(new double[n]), Vy(new double[n]),
charge(new double[n]), mass(new double[n]),
forceX(new double[n]), forceY(new double[n]),
xCache(new __m128d[n/2]), yCache(new __m128d[n/2]),
VxCache(new __m128d[n/2]), VyCache(new __m128d[n/2]) {}

Cloud::~Cloud()
{
	delete[] k1; delete[] k2; delete[] k3; delete[] k4;
	delete[] l1; delete[] l2; delete[] l3; delete[] l4;
	delete[] m1; delete[] m2; delete[] m3; delete[] m4;
	delete[] n1; delete[] n2; delete[] n3; delete[] n4;
	delete[] x; delete[] y; delete[] Vx; delete[] Vy;
	delete[] charge; delete[] mass;
	delete[] forceX; delete[] forceY;
	delete[] xCache; delete[] yCache;
	delete[] VxCache; delete[] VyCache;
}

inline void Cloud::setPosition(const cloud_index index, const double xVal, const double yVal)
{
	x[index] = xVal;
	y[index] = yVal;
}

inline void Cloud::setVelocity(const cloud_index index)
{
	Vx[index] = 0.0;
	Vy[index] = 0.0;
}

inline void Cloud::setCharge()
{
	srand((int)time(NULL));
	for (cloud_index i = 0; i < n; i++)
		charge[i] = (rand()%201 + 5900)*1.6E-19;
}

inline void Cloud::setMass()
{
	const double radius = 1.45E-6;
	const double particleDensity = 2200.0;
	const double particleMass = (4.0/3.0)*M_PI*radius*radius*radius*particleDensity;
	for (cloud_index i = 0; i < n; i++)
		mass[i] = particleMass;
}

Cloud * const Cloud::initializeGrid(const cloud_index numParticles)
{
	Cloud * const cloud = new Cloud(numParticles);

	const cloud_index sqrtNumPar = (cloud_index)floor(sqrt(numParticles));

	// For even numbers of partciles on a row center the row over the origin.
	const double cloudHalfSize = (double)sqrtNumPar/2.0*interParticleSpacing
		- ((sqrtNumPar%2) ? interParticleSpacing/2.0 : 0.0); // cloud halfwidth.

	cloud->setCharge();
	cloud->setMass();
	for (cloud_index i = 0; i < numParticles; i++)
	{
		cloud->setPosition(i,
			cloudHalfSize - (double)(i%sqrtNumPar)*interParticleSpacing,
			cloudHalfSize - (double)(i/sqrtNumPar)*interParticleSpacing);
		cloud->setVelocity(i);
	}

	return cloud;
}

Cloud * const Cloud::initializeFromFile(fitsfile * const file, int * const error, double * const currentTime)
{
	int *anyNull = NULL;
	long numParticles = 0;
	long numTimeSteps = 0;

	// move to CLOUD HDU:
	if (!*error)
		fits_movnam_hdu(file, BINARY_TBL, const_cast<char *> ("CLOUD"), 0, error);

	// get number of particles:
	if (!*error)
		fits_get_num_rows(file, &numParticles, error);

	// create cloud:
	Cloud * const cloud = new Cloud((cloud_index)numParticles); // cloudSize not used in this case, so set to zero

	// read mass and charge information:
	if (!*error)
	{
		// file, column #, starting row, first element, num elements, mass array, pointless pointer, error
		fits_read_col_dbl(file, 1, 1, 1, numParticles, 0.0, cloud->charge, anyNull, error);
		fits_read_col_dbl(file, 2, 1, 1, numParticles, 0.0, cloud->mass, anyNull, error);
	}

	// move to TIME_STEP HDU:
	if (!*error)
		fits_movnam_hdu(file, BINARY_TBL, const_cast<char *> ("TIME_STEP"), 0, error);

	// get number of time steps:
	if (!*error)
		fits_get_num_rows(file, &numTimeSteps, error);

	if (!*error)
	{
		if (currentTime)
			fits_read_col_dbl(file, 1, numTimeSteps, 1, 1, 0.0, currentTime, anyNull, error);

		fits_read_col_dbl(file, 2, numTimeSteps, 1, numParticles, 0.0, cloud->x, anyNull, error);
		fits_read_col_dbl(file, 3, numTimeSteps, 1, numParticles, 0.0, cloud->y, anyNull, error);
		fits_read_col_dbl(file, 4, numTimeSteps, 1, numParticles, 0.0, cloud->Vx, anyNull, error);
		fits_read_col_dbl(file, 5, numTimeSteps, 1, numParticles, 0.0, cloud->Vy, anyNull, error);
	}

	return cloud;
}

void Cloud::writeCloudSetup(fitsfile * const file, int * const error) const
{
	// format number of elements of type double as string, e.g. 1024D
	stringstream numStream;
	numStream << n << "D";
	const string numString = numStream.str();

	char *ttypeCloud[] = {const_cast<char *> ("CHARGE"), const_cast<char *> ("MASS")};
	char *tformCloud[] = {const_cast<char *> ("D"), const_cast<char *> ("D")};
	char *tunitCloud[] = {const_cast<char *> ("C"), const_cast<char *> ("kg")};

	char *ttypeRun[] = {const_cast<char *> ("TIME"),
		const_cast<char *> ("X_POSITION"), const_cast<char *> ("Y_POSITION"),
		const_cast<char *> ("X_VELOCITY"), const_cast<char *> ("Y_VELOCITY")};
	char *tformRun[] = {const_cast<char *> ("D"),
		const_cast<char *> (numString.c_str()), const_cast<char *> (numString.c_str()),
		const_cast<char *> (numString.c_str()), const_cast<char *> (numString.c_str())};
	char *tunitRun[] = {const_cast<char *> ("s"),
		const_cast<char *> ("m"), const_cast<char *> ("m"),
		const_cast<char *> ("m/s"), const_cast<char *> ("m/s")};

	// write mass and charge:
	if (!*error)
		// file, storage type, num rows, num columns, ...
		fits_create_tbl(file, BINARY_TBL, n, 2, ttypeCloud, tformCloud, tunitCloud, "CLOUD", error);
	if (!*error)
	{
		// file, column #, starting row, first element, num elements, mass array, error
		fits_write_col_dbl(file, 1, 1, 1, n, charge, error);
		fits_write_col_dbl(file, 2, 1, 1, n, mass, error);
	}

	// write position and velocity:
	if (!*error)
		fits_create_tbl(file, BINARY_TBL, 0, 5, ttypeRun, tformRun, tunitRun, "TIME_STEP", error);
		// n.b. num rows automatically incremented.
		// Increment from 0 as opposed to preallocating to ensure
		// proper output in the event of program interruption.
	if (!*error)
	{
		double time = 0.0;
		fits_write_col_dbl(file, 1, 1, 1, 1, &time, error);
		fits_write_col_dbl(file, 2, 1, 1, n, x, error);
		fits_write_col_dbl(file, 3, 1, 1, n, y, error);
		fits_write_col_dbl(file, 4, 1, 1, n, Vx, error);
		fits_write_col_dbl(file, 5, 1, 1, n, Vy, error);
	}

	// write buffer, close file, reopen at same point:
	fits_flush_file(file, error);
}

void Cloud::writeTimeStep(fitsfile * const file, int * const error, double currentTime) const
{
	if (!*error)
	{
		long numRows = 0;
		fits_get_num_rows(file, &numRows, error);
		fits_write_col_dbl(file, 1, ++numRows, 1, 1, &currentTime, error);
		fits_write_col_dbl(file, 2, numRows, 1, n, x, error);
		fits_write_col_dbl(file, 3, numRows, 1, n, y, error);
		fits_write_col_dbl(file, 4, numRows, 1, n, Vx, error);
		fits_write_col_dbl(file, 5, numRows, 1, n, Vy, error);
	}

	// write buffer, close file, reopen at same point:
	fits_flush_file(file, error);
}

// 4th order Runge-Kutta subsetp helper methods.

// X position helper functions -------------------------------------------------
const __m128d Cloud::getx1_pd(const cloud_index i) const
{
	// x
	return _mm_load_pd(x + i);
}

const __m128d Cloud::getx2_pd(const cloud_index i) const
{
	// x + l1/2
	return xCache[i/2];
}

const __m128d Cloud::getx3_pd(const cloud_index i) const
{
	// x + l2/2
	return xCache[i/2];
}

const __m128d Cloud::getx4_pd(const cloud_index i) const
{
	// x + l3
	return xCache[i/2];
}

const __m128d Cloud::getx1r_pd(const cloud_index i) const
{
	return _mm_loadr_pd(x + i);
}

const __m128d Cloud::getx2r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(xCache[j], xCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::getx3r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(xCache[j], xCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::getx4r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(xCache[j], xCache[j], _MM_SHUFFLE2(0, 1));
}

// Y position helper functions -------------------------------------------------
const __m128d Cloud::gety1_pd(const cloud_index i) const
{
	// y
	return _mm_load_pd(y + i);
}

const __m128d Cloud::gety2_pd(const cloud_index i) const
{
	// y + n1/2
	return yCache[i/2];
}

const __m128d Cloud::gety3_pd(const cloud_index i) const
{
	// y + n2/2
	return yCache[i/2];
}

const __m128d Cloud::gety4_pd(const cloud_index i) const
{
	// y + n3
	return yCache[i/2];
}

const __m128d Cloud::gety1r_pd(const cloud_index i) const
{
	return _mm_loadr_pd(y + i);
}

const __m128d Cloud::gety2r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(yCache[j], yCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::gety3r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(yCache[j], yCache[j], _MM_SHUFFLE2(0, 1));
}

const __m128d Cloud::gety4r_pd(const cloud_index i) const
{
	const cloud_index j = i/2;
	return _mm_shuffle_pd(yCache[j], yCache[j], _MM_SHUFFLE2(0, 1));
}

// Vx position helper functions ------------------------------------------------
const __m128d Cloud::getVx1_pd(const cloud_index i) const
{
	// Vx
	return _mm_load_pd(Vx + i);
}

const __m128d Cloud::getVx2_pd(const cloud_index i) const
{
	// Vx + k1/2
	return VxCache[i/2];
}

const __m128d Cloud::getVx3_pd(const cloud_index i) const
{
	// Vx + k2/2
	return VxCache[i/2];
}

const __m128d Cloud::getVx4_pd(const cloud_index i) const
{
	// Vx + k3
	return VxCache[i/2];
}

// Vy position helper functions ------------------------------------------------
const __m128d Cloud::getVy1_pd(const cloud_index i) const
{
	// Vy
	return _mm_load_pd(Vy + i);
}

const __m128d Cloud::getVy2_pd(const cloud_index i) const
{
	// Vy + m1/2
	return VyCache[i/2];
}

const __m128d Cloud::getVy3_pd(const cloud_index i) const
{
	// Vy + m2/2
	return VyCache[i/2];
}

const __m128d Cloud::getVy4_pd(const cloud_index i) const
{
	// Vy + m3
	return VyCache[i/2];
}
<|endoftext|>


<commit_before>/*
 * File:   Curve.cpp
 * Author: cameron
 *
 * Created on October 22, 2013, 1:07 AM
 */

#include "Curve.h"

// If this wasn't in program memory, we'd run out of SRAM way to fast.
const uint8_t Curve::etable[256] PROGMEM = {
   0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
   1,  1,  1,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
   2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  3,  3,  3,  3,  3,
   3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,  4,  4,
   4,  4,  4,  4,  4,  4,  5,  5,  5,  5,  5,  5,  5,  5,  5,  6,
   6,  6,  6,  6,  6,  6,  6,  7,  7,  7,  7,  7,  7,  8,  8,  8,
   8,  8,  8,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 11, 11, 11,
  11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 16,
  16, 16, 17, 17, 18, 18, 18, 19, 19, 20, 20, 21, 21, 21, 22, 22,
  23, 23, 24, 24, 25, 25, 26, 27, 27, 28, 28, 29, 30, 30, 31, 32,
  32, 33, 34, 35, 35, 36, 37, 38, 39, 39, 40, 41, 42, 43, 44, 45,
  46, 47, 48, 49, 50, 51, 52, 53, 55, 56, 57, 58, 59, 61, 62, 63,
  65, 66, 68, 69, 71, 72, 74, 76, 77, 79, 81, 82, 84, 86, 88, 90,
  92, 94, 96, 98,100,102,105,107,109,112,114,117,119,122,124,127,
 130,133,136,139,142,145,148,151,155,158,162,165,169,172,176,180,
 184,188,192,196,201,205,210,214,219,224,229,234,239,244,250,255,
};

uint8_t Curve::exponential(uint8_t i) {
 // If the compiler could build the above table for us, we could have "simply":
 //return !i ? 0 : round(exp(log(MAXOUTPUT) * i / MAXINPUT));

 // Need to read the table in a special way!
 return pgm_read_byte(&table[i]);
}

uint8_t Curve::linear(uint8_t i) {
 return i;
}

uint8_t Curve::reverse(uint8_t i) {
 return 255-i;
}<commit_msg>Fix per issue #2<commit_after>/*
 * File:   Curve.cpp
 * Author: cameron
 *
 * Created on October 22, 2013, 1:07 AM
 */

#include "Curve.h"

// If this wasn't in program memory, we'd run out of SRAM way to fast.
const uint8_t Curve::etable[256] PROGMEM = {
   0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
   1,  1,  1,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
   2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  3,  3,  3,  3,  3,
   3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,  4,  4,
   4,  4,  4,  4,  4,  4,  5,  5,  5,  5,  5,  5,  5,  5,  5,  6,
   6,  6,  6,  6,  6,  6,  6,  7,  7,  7,  7,  7,  7,  8,  8,  8,
   8,  8,  8,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 11, 11, 11,
  11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 16,
  16, 16, 17, 17, 18, 18, 18, 19, 19, 20, 20, 21, 21, 21, 22, 22,
  23, 23, 24, 24, 25, 25, 26, 27, 27, 28, 28, 29, 30, 30, 31, 32,
  32, 33, 34, 35, 35, 36, 37, 38, 39, 39, 40, 41, 42, 43, 44, 45,
  46, 47, 48, 49, 50, 51, 52, 53, 55, 56, 57, 58, 59, 61, 62, 63,
  65, 66, 68, 69, 71, 72, 74, 76, 77, 79, 81, 82, 84, 86, 88, 90,
  92, 94, 96, 98,100,102,105,107,109,112,114,117,119,122,124,127,
 130,133,136,139,142,145,148,151,155,158,162,165,169,172,176,180,
 184,188,192,196,201,205,210,214,219,224,229,234,239,244,250,255,
};

uint8_t Curve::exponential(uint8_t i) {
 // If the compiler could build the above table for us, we could have "simply":
 //return !i ? 0 : round(exp(log(MAXOUTPUT) * i / MAXINPUT));

 // Need to read the table in a special way!
 return pgm_read_byte(&etable[i]);
}

uint8_t Curve::linear(uint8_t i) {
 return i;
}

uint8_t Curve::reverse(uint8_t i) {
 return 255-i;
}
<|endoftext|>


<commit_before>#include <bigg.hpp>

#ifdef _WIN32
#	define GLFW_EXPOSE_NATIVE_WIN32
#endif
#ifdef __APPLE__
#	define GLFW_EXPOSE_NATIVE_COCOA
#endif
#include <bx/fpumath.h>
#include <bgfx/platform.h>
#include <GLFW/glfw3native.h>
#include <glm/glm.hpp>
#include <fstream>

#include "bigg_assets.h"
#include "bigg_shaders.hpp"
#include "bigg_imgui.hpp"

// bgfx utils

const bgfx::Memory* bigg::loadMemory( const char* filename )
{
	std::ifstream file( filename, std::ios::binary | std::ios::ate );
	std::streamsize size = file.tellg();
	file.seekg( 0, std::ios::beg );
	const bgfx::Memory* mem = bgfx::alloc( uint32_t( size + 1 ) );
	if ( file.read( ( char* )mem->data, size ) )
	{
		mem->data[ mem->size - 1 ] = '\0';
		return mem;
	}
	return nullptr;
}

bgfx::ShaderHandle bigg::loadShader( const char* shader )
{
	return bgfx::createShader( loadMemory( shader ) );
}

bgfx::ProgramHandle bigg::loadProgram( const char* vsName, const char* fsName )
{
	bgfx::ShaderHandle vs = loadShader( vsName );
	bgfx::ShaderHandle fs = loadShader( fsName );
	return bgfx::createProgram( vs, fs, true );
}

// application

void bigg::Application::mouseButtonCallback( GLFWwindow* window, int button, int action, int mods )
{
	bigg::Application* app = ( bigg::Application* )glfwGetWindowUserPointer( window );
	if ( action == GLFW_PRESS && button >= 0 && button < 3 )
	{
		app->mMousePressed[button] = true;
	}
}

void bigg::Application::scrollCallback(GLFWwindow* window, double xoffset, double yoffset)
{
	bigg::Application* app = ( bigg::Application* )glfwGetWindowUserPointer( window );
	app->mMouseWheel += (float)yoffset;
}

void bigg::Application::keyCallback( GLFWwindow*, int key, int, int action, int mods )
{
	ImGuiIO& io = ImGui::GetIO();
	if ( action == GLFW_PRESS )
	{
		io.KeysDown[ key ] = true;
	}
	if ( action == GLFW_RELEASE )
	{
		io.KeysDown[ key ] = false;
	}
	io.KeyCtrl = io.KeysDown[ GLFW_KEY_LEFT_CONTROL ] || io.KeysDown[ GLFW_KEY_RIGHT_CONTROL ];
	io.KeyShift = io.KeysDown[ GLFW_KEY_LEFT_SHIFT ] || io.KeysDown[ GLFW_KEY_RIGHT_SHIFT ];
	io.KeyAlt = io.KeysDown[ GLFW_KEY_LEFT_ALT ] || io.KeysDown[ GLFW_KEY_RIGHT_ALT ];
	io.KeySuper = io.KeysDown[ GLFW_KEY_LEFT_SUPER ] || io.KeysDown[ GLFW_KEY_RIGHT_SUPER ];
}

void bigg::Application::charCallback(GLFWwindow*, unsigned int c)
{
	ImGuiIO& io = ImGui::GetIO();
	if ( c > 0 && c < 0x10000 )
	{
		io.AddInputCharacter( ( unsigned short )c );
	}
}

void bigg::Application::imguiEvents( float dt )
{
	ImGuiIO& io = ImGui::GetIO();
	io.DeltaTime = dt;
	int w, h;
	int displayW, displayH;
	glfwGetWindowSize( mWindow, &w, &h );
	glfwGetFramebufferSize( mWindow, &displayW, &displayH );
	io.DisplaySize = ImVec2( ( float )w, ( float )h );
	io.DisplayFramebufferScale = ImVec2( w > 0 ? ( ( float )displayW / w ) : 0, h > 0 ? ( ( float )displayH / h ) : 0 );
	if ( glfwGetWindowAttrib( mWindow, GLFW_FOCUSED ) )
	{
		double mouse_x, mouse_y;
		glfwGetCursorPos( mWindow, &mouse_x, &mouse_y );
		io.MousePos = ImVec2( ( float )mouse_x, ( float )mouse_y );
	}
	else
	{
		io.MousePos = ImVec2( -1, -1 );
	}
	for (int i = 0; i < 3; i++)
	{
		io.MouseDown[ i ] = mMousePressed[ i ] || glfwGetMouseButton( mWindow, i ) != 0;
		mMousePressed[ i ] = false;
	}
	io.MouseWheel = mMouseWheel;
	mMouseWheel = 0.0f;
	glfwSetInputMode( mWindow, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL );
	io.ClipboardUserData = mWindow;
#ifdef _WIN32
	io.ImeWindowHandle = glfwGetWin32Window( mWindow );
#endif
}

bigg::Application::Application()
{
	mMousePressed[ 0 ] = false;
	mMousePressed[ 1 ] = false;
	mMousePressed[ 2 ] = false;
	mMouseWheel = 0.0f;
}

int bigg::Application::run( int argc, char** argv, bgfx::RendererType::Enum type, uint16_t vendorId, uint16_t deviceId, bgfx::CallbackI* callback, bx::AllocatorI* allocator )
{
	// Initialize the glfw
	if ( !glfwInit() )
	{
		return -1;
	}

	// Create a window
	glfwWindowHint( GLFW_CLIENT_API, GLFW_NO_API );
	mWindow = glfwCreateWindow( 1280, 768, "", NULL, NULL );
	if ( !mWindow )
	{
		glfwTerminate();
		return -1;
	}

	// Setup input callbacks
	glfwSetWindowUserPointer( mWindow, this );
	glfwSetMouseButtonCallback( mWindow, mouseButtonCallback );
	glfwSetScrollCallback( mWindow, scrollCallback );
	glfwSetKeyCallback( mWindow, keyCallback );
	glfwSetCharCallback( mWindow, charCallback );

	// Setup bgfx
	bgfx::PlatformData platformData;
	memset( &platformData, 0, sizeof( platformData ) );
#	ifdef _WIN32
	platformData.nwh = glfwGetWin32Window( mWindow );
#	endif
#	ifdef __APPLE__
	platformData.nwh = glfwGetCocoaWindow( mWindow );
#	endif
	bgfx::setPlatformData( platformData );
	bgfx::init( type, vendorId, deviceId, callback, allocator );

	// Setup vertex declarations
	bigg::PosColorVertex::init();

	// Setup ImGui
	imguiInit();

	// Initialize the application
	reset();
	initialize( argc, argv );

	// Loop until the user closes the window
	float lastTime = 0;
	float dt;
	float time;
	while ( !glfwWindowShouldClose( mWindow ) )
	{
		time = ( float )glfwGetTime();
		dt = time - lastTime;
		lastTime = time;

		glfwPollEvents();
		imguiEvents( dt );
		ImGui::NewFrame();
		update( dt );
		ImGui::Render();
		bgfx::frame();

		int w, h;
		glfwGetWindowSize( mWindow, &w, &h );
		if ( w != mWidth || h != mHeight )
		{
			mWidth = w;
			mHeight = h;
			reset();
		}
	}

	// Shutdown application and glfw
	int ret = shutdown();
	imguiShutdown();
	bgfx::shutdown();
	glfwTerminate();
	return ret;
}

void bigg::Application::reset( uint32_t flags )
{
	mReset = flags;
	bgfx::reset( mWidth, mHeight, mReset );
	onReset();
}

uint32_t bigg::Application::getWidth()
{
	return mWidth;
}

uint32_t bigg::Application::getHeight()
{
	return mHeight;
}

void bigg::PosColorVertex::init()
{
	ms_decl
		.begin()
		.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
		.add(bgfx::Attrib::Color0,   4, bgfx::AttribType::Uint8, true)
		.end();
};
bgfx::VertexDecl bigg::PosColorVertex::ms_decl;<commit_msg>Fix losing reset flags<commit_after>#include <bigg.hpp>

#ifdef _WIN32
#	define GLFW_EXPOSE_NATIVE_WIN32
#endif
#ifdef __APPLE__
#	define GLFW_EXPOSE_NATIVE_COCOA
#endif
#include <bx/fpumath.h>
#include <bgfx/platform.h>
#include <GLFW/glfw3native.h>
#include <glm/glm.hpp>
#include <fstream>

#include "bigg_assets.h"
#include "bigg_shaders.hpp"
#include "bigg_imgui.hpp"

// bgfx utils

const bgfx::Memory* bigg::loadMemory( const char* filename )
{
	std::ifstream file( filename, std::ios::binary | std::ios::ate );
	std::streamsize size = file.tellg();
	file.seekg( 0, std::ios::beg );
	const bgfx::Memory* mem = bgfx::alloc( uint32_t( size + 1 ) );
	if ( file.read( ( char* )mem->data, size ) )
	{
		mem->data[ mem->size - 1 ] = '\0';
		return mem;
	}
	return nullptr;
}

bgfx::ShaderHandle bigg::loadShader( const char* shader )
{
	return bgfx::createShader( loadMemory( shader ) );
}

bgfx::ProgramHandle bigg::loadProgram( const char* vsName, const char* fsName )
{
	bgfx::ShaderHandle vs = loadShader( vsName );
	bgfx::ShaderHandle fs = loadShader( fsName );
	return bgfx::createProgram( vs, fs, true );
}

// application

void bigg::Application::mouseButtonCallback( GLFWwindow* window, int button, int action, int mods )
{
	bigg::Application* app = ( bigg::Application* )glfwGetWindowUserPointer( window );
	if ( action == GLFW_PRESS && button >= 0 && button < 3 )
	{
		app->mMousePressed[button] = true;
	}
}

void bigg::Application::scrollCallback(GLFWwindow* window, double xoffset, double yoffset)
{
	bigg::Application* app = ( bigg::Application* )glfwGetWindowUserPointer( window );
	app->mMouseWheel += (float)yoffset;
}

void bigg::Application::keyCallback( GLFWwindow*, int key, int, int action, int mods )
{
	ImGuiIO& io = ImGui::GetIO();
	if ( action == GLFW_PRESS )
	{
		io.KeysDown[ key ] = true;
	}
	if ( action == GLFW_RELEASE )
	{
		io.KeysDown[ key ] = false;
	}
	io.KeyCtrl = io.KeysDown[ GLFW_KEY_LEFT_CONTROL ] || io.KeysDown[ GLFW_KEY_RIGHT_CONTROL ];
	io.KeyShift = io.KeysDown[ GLFW_KEY_LEFT_SHIFT ] || io.KeysDown[ GLFW_KEY_RIGHT_SHIFT ];
	io.KeyAlt = io.KeysDown[ GLFW_KEY_LEFT_ALT ] || io.KeysDown[ GLFW_KEY_RIGHT_ALT ];
	io.KeySuper = io.KeysDown[ GLFW_KEY_LEFT_SUPER ] || io.KeysDown[ GLFW_KEY_RIGHT_SUPER ];
}

void bigg::Application::charCallback(GLFWwindow*, unsigned int c)
{
	ImGuiIO& io = ImGui::GetIO();
	if ( c > 0 && c < 0x10000 )
	{
		io.AddInputCharacter( ( unsigned short )c );
	}
}

void bigg::Application::imguiEvents( float dt )
{
	ImGuiIO& io = ImGui::GetIO();
	io.DeltaTime = dt;
	int w, h;
	int displayW, displayH;
	glfwGetWindowSize( mWindow, &w, &h );
	glfwGetFramebufferSize( mWindow, &displayW, &displayH );
	io.DisplaySize = ImVec2( ( float )w, ( float )h );
	io.DisplayFramebufferScale = ImVec2( w > 0 ? ( ( float )displayW / w ) : 0, h > 0 ? ( ( float )displayH / h ) : 0 );
	if ( glfwGetWindowAttrib( mWindow, GLFW_FOCUSED ) )
	{
		double mouse_x, mouse_y;
		glfwGetCursorPos( mWindow, &mouse_x, &mouse_y );
		io.MousePos = ImVec2( ( float )mouse_x, ( float )mouse_y );
	}
	else
	{
		io.MousePos = ImVec2( -1, -1 );
	}
	for (int i = 0; i < 3; i++)
	{
		io.MouseDown[ i ] = mMousePressed[ i ] || glfwGetMouseButton( mWindow, i ) != 0;
		mMousePressed[ i ] = false;
	}
	io.MouseWheel = mMouseWheel;
	mMouseWheel = 0.0f;
	glfwSetInputMode( mWindow, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL );
	io.ClipboardUserData = mWindow;
#ifdef _WIN32
	io.ImeWindowHandle = glfwGetWin32Window( mWindow );
#endif
}

bigg::Application::Application()
{
	mMousePressed[ 0 ] = false;
	mMousePressed[ 1 ] = false;
	mMousePressed[ 2 ] = false;
	mMouseWheel = 0.0f;
}

int bigg::Application::run( int argc, char** argv, bgfx::RendererType::Enum type, uint16_t vendorId, uint16_t deviceId, bgfx::CallbackI* callback, bx::AllocatorI* allocator )
{
	// Initialize the glfw
	if ( !glfwInit() )
	{
		return -1;
	}

	// Create a window
	glfwWindowHint( GLFW_CLIENT_API, GLFW_NO_API );
	mWindow = glfwCreateWindow( 1280, 768, "", NULL, NULL );
	if ( !mWindow )
	{
		glfwTerminate();
		return -1;
	}

	// Setup input callbacks
	glfwSetWindowUserPointer( mWindow, this );
	glfwSetMouseButtonCallback( mWindow, mouseButtonCallback );
	glfwSetScrollCallback( mWindow, scrollCallback );
	glfwSetKeyCallback( mWindow, keyCallback );
	glfwSetCharCallback( mWindow, charCallback );

	// Setup bgfx
	bgfx::PlatformData platformData;
	memset( &platformData, 0, sizeof( platformData ) );
#	ifdef _WIN32
	platformData.nwh = glfwGetWin32Window( mWindow );
#	endif
#	ifdef __APPLE__
	platformData.nwh = glfwGetCocoaWindow( mWindow );
#	endif
	bgfx::setPlatformData( platformData );
	bgfx::init( type, vendorId, deviceId, callback, allocator );

	// Setup vertex declarations
	bigg::PosColorVertex::init();

	// Setup ImGui
	imguiInit();

	// Initialize the application
	reset();
	initialize( argc, argv );

	// Loop until the user closes the window
	float lastTime = 0;
	float dt;
	float time;
	while ( !glfwWindowShouldClose( mWindow ) )
	{
		time = ( float )glfwGetTime();
		dt = time - lastTime;
		lastTime = time;

		glfwPollEvents();
		imguiEvents( dt );
		ImGui::NewFrame();
		update( dt );
		ImGui::Render();
		bgfx::frame();

		int w, h;
		glfwGetWindowSize( mWindow, &w, &h );
		if ( w != mWidth || h != mHeight )
		{
			mWidth = w;
			mHeight = h;
			reset( mReset );
		}
	}

	// Shutdown application and glfw
	int ret = shutdown();
	imguiShutdown();
	bgfx::shutdown();
	glfwTerminate();
	return ret;
}

void bigg::Application::reset( uint32_t flags )
{
	mReset = flags;
	bgfx::reset( mWidth, mHeight, mReset );
	onReset();
}

uint32_t bigg::Application::getWidth()
{
	return mWidth;
}

uint32_t bigg::Application::getHeight()
{
	return mHeight;
}

void bigg::PosColorVertex::init()
{
	ms_decl
		.begin()
		.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
		.add(bgfx::Attrib::Color0,   4, bgfx::AttribType::Uint8, true)
		.end();
};
bgfx::VertexDecl bigg::PosColorVertex::ms_decl;<|endoftext|>


<commit_before>#include <stdio.h>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <set>
#include <string>
#include <queue>
#include <iostream>
#include "CallGraph.h"
#include "CodeGen_Bash.h"
#include "Parser.h"
#include "IRVisitor.h"

const std::string BISH_VERSION = "0.1";
const std::string BISH_URL = "https://github.com/tdenniston/bish";
const std::string STDLIB_PATH = "src/StdLib.bish";

class FindFunctionCalls : public Bish::IRVisitor {
public:
    FindFunctionCalls(const std::set<std::string> &n) {
        to_find.insert(n.begin(), n.end());
    }

    std::set<std::string> names() { return names_; }

    virtual void visit(Bish::FunctionCall *call) {
        for (std::vector<Bish::IRNode *>::const_iterator I = call->args.begin(),
                 E = call->args.end(); I != E; ++I) {
            (*I)->accept(this);
        }
        if (to_find.count(call->function->name)) {
            names_.insert(call->function->name);
        }
    }
private:
    std::set<std::string> to_find;
    std::set<std::string> names_;
};

// Return the path to the standard library. This tries a couple of
// options before falling back on the hardcoded value.
std::string get_stdlib_path() {
    char abspath[PATH_MAX];
    char *root = std::getenv("BISH_ROOT");
    char *stdlib = std::getenv("BISH_STDLIB");
    if (root) {
        root = realpath(root, abspath);
        assert(root);
        return std::string(abspath) + "/" + STDLIB_PATH;
    } else if (stdlib) {
        stdlib = realpath(stdlib, abspath);
        assert(stdlib);
        return std::string(abspath);
    } else {
        return STDLIB_PATH;
    }
}

// Add necessary stdlib functions to the given module.
void link_stdlib(Bish::Module *m) {
    Bish::Parser p;
    Bish::Module *stdlib = p.parse(get_stdlib_path());
    std::set<std::string> stdlib_functions;
    for (std::vector<Bish::Function *>::iterator I = stdlib->functions.begin(),
             E = stdlib->functions.end(); I != E; ++I) {
        Bish::Function *f = *I;
        if (f->name.compare("main") == 0) continue;
        stdlib_functions.insert(f->name);
    }
    FindFunctionCalls find(stdlib_functions);
    m->accept(&find);
    Bish::CallGraphBuilder cgb;
    Bish::CallGraph cg = cgb.build(stdlib);

    std::set<std::string> to_link = find.names();
    for (std::set<std::string>::iterator I = to_link.begin(), E = to_link.end(); I != E; ++I) {
        Bish::Function *f = stdlib->get_function(*I);
        assert(f);
        if (f->name.compare("main") == 0) continue;
        m->add_function(f);
        std::vector<Bish::Function *> calls = cg.transitive_calls(f);
        for (std::vector<Bish::Function *>::iterator II = calls.begin(), EE = calls.end(); II != EE; ++II) {
            m->add_function(stdlib->get_function((*II)->name));
        }
    }
}

void compile_to_bash(std::ostream &os, Bish::Module *m) {
    link_stdlib(m);
    os << "#!/usr/bin/env bash\n";
    os << "# Autogenerated script, compiled from the Bish language.\n";
    os << "# Bish version " << BISH_VERSION << "\n";
    os << "# Please see " << BISH_URL << " for more information about Bish.\n\n";
    Bish::CodeGen_Bash compile(os);
    m->accept(&compile);
}

void run_on_bash(std::istream &is) {
    FILE *bash = popen("bash", "w");
    char buf[4096];

    do {
        is.read(buf, sizeof(buf));
        fwrite(buf, 1, is.gcount(), bash);
    } while (is.gcount() > 0);

    fflush(bash);
    pclose(bash);
}

int main(int argc, char **argv) {
    if (argc < 2) {
        std::cerr << "USAGE: " << argv[0] << " [-r] <INPUT>\n";
        std::cerr << "  Compiles Bish file <INPUT> to bash.\n";
        std::cerr << "\nOPTIONS:\n";
        std::cerr << "  -r  compiles and runs the file.\n";
        return 1;
    }

    if (strcmp(argv[1], "-r") == 0) {
        if (argc != 3) {
            std::cerr << "-r needs a filename\n";
            return 1;
        }

        std::string path(argv[2]);
        Bish::Parser p;
        Bish::Module *m = p.parse(path);

        std::stringstream s;
        compile_to_bash(s, m);
        run_on_bash(s);
    } else {
        std::string path(argv[1]);
        Bish::Parser p;
        Bish::Module *m = p.parse(path);

        compile_to_bash(std::cout, m);
    }

    return 0;
}
<commit_msg>Fix build error due to PATH_MAX.<commit_after>#include <stdio.h>
#include <limits.h>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <set>
#include <string>
#include <queue>
#include <iostream>
#include "CallGraph.h"
#include "CodeGen_Bash.h"
#include "Parser.h"
#include "IRVisitor.h"

const std::string BISH_VERSION = "0.1";
const std::string BISH_URL = "https://github.com/tdenniston/bish";
const std::string STDLIB_PATH = "src/StdLib.bish";

class FindFunctionCalls : public Bish::IRVisitor {
public:
    FindFunctionCalls(const std::set<std::string> &n) {
        to_find.insert(n.begin(), n.end());
    }

    std::set<std::string> names() { return names_; }

    virtual void visit(Bish::FunctionCall *call) {
        for (std::vector<Bish::IRNode *>::const_iterator I = call->args.begin(),
                 E = call->args.end(); I != E; ++I) {
            (*I)->accept(this);
        }
        if (to_find.count(call->function->name)) {
            names_.insert(call->function->name);
        }
    }
private:
    std::set<std::string> to_find;
    std::set<std::string> names_;
};

// Return the path to the standard library. This tries a couple of
// options before falling back on the hardcoded value.
std::string get_stdlib_path() {
    char abspath[PATH_MAX];
    char *root = std::getenv("BISH_ROOT");
    char *stdlib = std::getenv("BISH_STDLIB");
    if (root) {
        root = realpath(root, abspath);
        assert(root);
        return std::string(abspath) + "/" + STDLIB_PATH;
    } else if (stdlib) {
        stdlib = realpath(stdlib, abspath);
        assert(stdlib);
        return std::string(abspath);
    } else {
        return STDLIB_PATH;
    }
}

// Add necessary stdlib functions to the given module.
void link_stdlib(Bish::Module *m) {
    Bish::Parser p;
    Bish::Module *stdlib = p.parse(get_stdlib_path());
    std::set<std::string> stdlib_functions;
    for (std::vector<Bish::Function *>::iterator I = stdlib->functions.begin(),
             E = stdlib->functions.end(); I != E; ++I) {
        Bish::Function *f = *I;
        if (f->name.compare("main") == 0) continue;
        stdlib_functions.insert(f->name);
    }
    FindFunctionCalls find(stdlib_functions);
    m->accept(&find);
    Bish::CallGraphBuilder cgb;
    Bish::CallGraph cg = cgb.build(stdlib);

    std::set<std::string> to_link = find.names();
    for (std::set<std::string>::iterator I = to_link.begin(), E = to_link.end(); I != E; ++I) {
        Bish::Function *f = stdlib->get_function(*I);
        assert(f);
        if (f->name.compare("main") == 0) continue;
        m->add_function(f);
        std::vector<Bish::Function *> calls = cg.transitive_calls(f);
        for (std::vector<Bish::Function *>::iterator II = calls.begin(), EE = calls.end(); II != EE; ++II) {
            m->add_function(stdlib->get_function((*II)->name));
        }
    }
}

void compile_to_bash(std::ostream &os, Bish::Module *m) {
    link_stdlib(m);
    os << "#!/usr/bin/env bash\n";
    os << "# Autogenerated script, compiled from the Bish language.\n";
    os << "# Bish version " << BISH_VERSION << "\n";
    os << "# Please see " << BISH_URL << " for more information about Bish.\n\n";
    Bish::CodeGen_Bash compile(os);
    m->accept(&compile);
}

void run_on_bash(std::istream &is) {
    FILE *bash = popen("bash", "w");
    char buf[4096];

    do {
        is.read(buf, sizeof(buf));
        fwrite(buf, 1, is.gcount(), bash);
    } while (is.gcount() > 0);

    fflush(bash);
    pclose(bash);
}

int main(int argc, char **argv) {
    if (argc < 2) {
        std::cerr << "USAGE: " << argv[0] << " [-r] <INPUT>\n";
        std::cerr << "  Compiles Bish file <INPUT> to bash.\n";
        std::cerr << "\nOPTIONS:\n";
        std::cerr << "  -r  compiles and runs the file.\n";
        return 1;
    }

    if (strcmp(argv[1], "-r") == 0) {
        if (argc != 3) {
            std::cerr << "-r needs a filename\n";
            return 1;
        }

        std::string path(argv[2]);
        Bish::Parser p;
        Bish::Module *m = p.parse(path);

        std::stringstream s;
        compile_to_bash(s, m);
        run_on_bash(s);
    } else {
        std::string path(argv[1]);
        Bish::Parser p;
        Bish::Module *m = p.parse(path);

        compile_to_bash(std::cout, m);
    }

    return 0;
}
<|endoftext|>


<commit_before>#ifndef __FRAME_HPP__
#define __FRAME_HPP__

#include "include/global.hpp"

#include <string>
#include <vector>

#define MAX_PAYLOAD_LENGTH             0x7FFFFFFFFFFFFFFF;

typedef unsigned int                   FrameMask;

namespace ws
{

struct Frame
{
	static const byte FinalBit = 0x80;
	static const byte ReservedBit1 = 0x40; // Compress Extension
	static const byte ReservedBit2 = 0x20;
	static const byte ReservedBit3 = 0x10;
	static const byte TypeMask = 0x0F;
	static const byte MaskBit = 0x80;
	static const byte PayloadLengthMask = 0x7F;

	static const int FrameMinSize = 2;
	static const int MaskKeySize = 4;

	static const int PayloadSizeDefault = 125;
	static const int PayloadSizeExtraWord = 126;
	static const int PayloadSizeExtraQWord = 127;

	// RFC 6455 OpCodes
	enum Type
	{
		CONTINIUATION                  = 0x0,
		TEXT                           = 0x1,
		BINARY                         = 0x2,

		// Reserved for further non-control Frames (RFC 6455)
		NCF1                           = 0x3,
		NCF2                           = 0x4,
		NCF3                           = 0x5,
		NCF4                           = 0x6,
		NCF5                           = 0x7,

		CLOSE                          = 0x8,
		PING                           = 0x9,
		PONG                           = 0xA,

		// Reserved for further control frames (RFC 6455)
		CF1                            = 0xB,
		CF2                            = 0xC,
		CF3                            = 0xD,

		INCOMPLETE                     = 0xE,

		// Reserved for further control frames (RFC 6455)
		CF4                            = 0xF,
	};

	enum ParseResult
	{
        OK,
        Incomplete,
        Error
    };

	bool final                         : 1;
	bool rsv1                          : 1;
	bool rsv2                          : 1;
	bool rsv3                          : 1;

	Type opcode                        : 4;

	bool masked                        : 1;
	unsigned short length              : 7;

	unsigned short extended            : 16;

	char *payload;

	bool IsControl();
	bool IsNonControl();
	bool IsReserved();

	bool Extended();

	static ParseResult Parse(char *data, size_t length, Frame &target, const char *end, std::string reason);

	Frame();
	Frame(Type opcode, bool final, bool masked, const char *payload, size_t length);
	void MakeData(std::vector<char> &data);

};

}

#endif<commit_msg>Fixed indentation.<commit_after>#ifndef __FRAME_HPP__
#define __FRAME_HPP__

#include "include/global.hpp"

#include <string>
#include <vector>

#define MAX_PAYLOAD_LENGTH             0x7FFFFFFFFFFFFFFF;

typedef unsigned int                   FrameMask;

namespace ws
{

struct Frame
{
	static const byte FinalBit = 0x80;
	static const byte ReservedBit1 = 0x40; // Compress Extension
	static const byte ReservedBit2 = 0x20;
	static const byte ReservedBit3 = 0x10;
	static const byte TypeMask = 0x0F;
	static const byte MaskBit = 0x80;
	static const byte PayloadLengthMask = 0x7F;

	static const int FrameMinSize = 2;
	static const int MaskKeySize = 4;

	static const int PayloadSizeDefault = 125;
	static const int PayloadSizeExtraWord = 126;
	static const int PayloadSizeExtraQWord = 127;

	// RFC 6455 OpCodes
	enum Type
	{
		CONTINIUATION                  = 0x0,
		TEXT                           = 0x1,
		BINARY                         = 0x2,

		// Reserved for further non-control Frames (RFC 6455)
		NCF1                           = 0x3,
		NCF2                           = 0x4,
		NCF3                           = 0x5,
		NCF4                           = 0x6,
		NCF5                           = 0x7,

		CLOSE                          = 0x8,
		PING                           = 0x9,
		PONG                           = 0xA,

		// Reserved for further control frames (RFC 6455)
		CF1                            = 0xB,
		CF2                            = 0xC,
		CF3                            = 0xD,

		INCOMPLETE                     = 0xE,

		// Reserved for further control frames (RFC 6455)
		CF4                            = 0xF,
	};

	enum ParseResult
	{
		OK,
		Incomplete,
		Error
	};

	bool final                         : 1;
	bool rsv1                          : 1;
	bool rsv2                          : 1;
	bool rsv3                          : 1;

	Type opcode                        : 4;

	bool masked                        : 1;
	unsigned short length              : 7;

	unsigned short extended            : 16;

	char *payload;

	bool IsControl();
	bool IsNonControl();
	bool IsReserved();

	bool Extended();

	static ParseResult Parse(char *data, size_t length, Frame &target, const char *end, std::string reason);

	Frame();
	Frame(Type opcode, bool final, bool masked, const char *payload, size_t length);
	void MakeData(std::vector<char> &data);

};

}

#endif<|endoftext|>


<commit_before>//	Copyright 2016, Laminar Research
//	This source code is licensed under the MIT open source license.
//	See LICENSE.txt for the full terms of the license.

#define VERSION "1.1.0r1"

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <vector>

#ifndef XPLM200
#define XPLM200
#endif

#ifndef XPLM210
#define XPLM210
#endif

#include <XPLMPlugin.h>
#include <XPLMDataAccess.h>
#include <XPLMUtilities.h>
#include <XPLMProcessing.h>

#include "module.h"
#include "xpdatarefs.h"
#include "xpcommands.h"
#include "xptimers.h"

using std::vector;

/*

	TODO: get good errors on compile error.
	TODO: pipe output somewhere useful.

 */

extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}

static vector<module *>g_modules;
static XPLMFlightLoopID	g_pre_loop = NULL;
static XPLMFlightLoopID	g_post_loop = NULL;
static int				g_is_acf_inited = 0;
XPLMDataRef				g_replay_active = NULL;
XPLMDataRef				g_sim_period = NULL;

struct lua_alloc_request_t {
			void *	ud;
			void *	ptr;
			size_t	osize;
			size_t	nsize;
};

#define		ALLOC_OPEN		0x00A110C1
#define		ALLOC_REALLOC	0x00A110C2
#define		ALLOC_CLOSE		0x00A110C3
#define		ALLOC_LOCK		0x00A110C4
#define		ALLOC_UNLOCK	0x00A110C5

static void lua_lock()
{
	XPLMSendMessageToPlugin(XPLM_PLUGIN_XPLANE, ALLOC_LOCK, NULL);
}
static void lua_unlock()
{
	XPLMSendMessageToPlugin(XPLM_PLUGIN_XPLANE, ALLOC_UNLOCK, NULL);
}

static void *lj_alloc_create(void)
{
	struct lua_alloc_request_t r = { 0 };
	XPLMSendMessageToPlugin(XPLM_PLUGIN_XPLANE, ALLOC_OPEN,&r);
	return r.ud;
}

static void  lj_alloc_destroy(void *msp)
{
	struct lua_alloc_request_t r = { 0 };
	r.ud = msp;
	XPLMSendMessageToPlugin(XPLM_PLUGIN_XPLANE, ALLOC_CLOSE,&r);
}

static void *lj_alloc_f(void *msp, void *ptr, size_t osize, size_t nsize)
{
	struct lua_alloc_request_t r = { 0 };
	r.ud = msp;
	r.ptr = ptr;
	r.osize = osize;
	r.nsize = nsize;
	XPLMSendMessageToPlugin(XPLM_PLUGIN_XPLANE, ALLOC_REALLOC,&r);
	return r.ptr;
}

static float xlua_pre_timer_master_cb(
                                   float                inElapsedSinceLastCall,
                                   float                inElapsedTimeSinceLastFlightLoop,
                                   int                  inCounter,
                                   void *               inRefcon)
{
	xlua_do_timers_for_time(xlua_get_simulated_time());

	if(XPLMGetDatai(g_replay_active) == 0)
	if(XPLMGetDataf(g_sim_period) > 0.0f)
	for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
		(*m)->pre_physics();
	return -1;
}

static float xlua_post_timer_master_cb(
                                   float                inElapsedSinceLastCall,
                                   float                inElapsedTimeSinceLastFlightLoop,
                                   int                  inCounter,
                                   void *               inRefcon)
{
	if(XPLMGetDatai(g_replay_active) == 0)
	{
		if(XPLMGetDataf(g_sim_period) > 0.0f)
		for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
			(*m)->post_physics();
	}
	else
	for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
		(*m)->post_replay();
	return -1;
}

PLUGIN_API int XPluginStart(
						char *		outName,
						char *		outSig,
						char *		outDesc)
{

    strcpy(outName, "XLua " VERSION);
    strcpy(outSig, "com.x-plane.xlua." VERSION);
    strcpy(outDesc, "A minimal scripting environment for aircraft authors.");

	g_replay_active = XPLMFindDataRef("sim/time/is_in_replay");
	g_sim_period = XPLMFindDataRef("sim/operation/misc/frame_rate_period");

	XPLMCreateFlightLoop_t pre = { 0 };
	XPLMCreateFlightLoop_t post = { 0 };
	pre.structSize = sizeof(pre);
	post.structSize = sizeof(post);
	pre.phase = xplm_FlightLoop_Phase_BeforeFlightModel;
	post.phase = xplm_FlightLoop_Phase_BeforeFlightModel;
	pre.callbackFunc = xlua_pre_timer_master_cb;
	post.callbackFunc = xlua_post_timer_master_cb;

	g_pre_loop = XPLMCreateFlightLoop(&pre);
	g_post_loop = XPLMCreateFlightLoop(&post);
	XPLMScheduleFlightLoop(g_pre_loop, -1, 0);
	XPLMScheduleFlightLoop(g_post_loop, -1, 0);

	XPLMEnableFeature("XPLM_USE_NATIVE_PATHS", 1);

	char path_to_me_c[2048];
	XPLMGetPluginInfo(XPLMGetMyID(), NULL, path_to_me_c, NULL, NULL);

	// Plugin base path: pop off two dirs from the plugin name to get the base path.
	string plugin_base_path(path_to_me_c);
	string::size_type lp = plugin_base_path.find_last_of("/\\");
	plugin_base_path.erase(lp);
	lp = plugin_base_path.find_last_of("/\\");
	plugin_base_path.erase(lp+1);

	string init_script_path(plugin_base_path);
	init_script_path += "init.lua";
	string scripts_dir_path(plugin_base_path);

	scripts_dir_path += "scripts";

	int offset = 0;
	int mf, fcount;
	while(1)
	{
		char fname_buf[2048];
		char * fptr;
		XPLMGetDirectoryContents(
								scripts_dir_path.c_str(),
								offset,
								fname_buf,
								sizeof(fname_buf),
								&fptr,
								1,
								&mf,
								&fcount);
		if(fcount == 0)
			break;

		if(strcmp(fptr, ".DS_Store") != 0)
		{
			string mod_path(scripts_dir_path);
			mod_path += "/";
			mod_path += fptr;
			mod_path += "/";
			string script_path(mod_path);
			script_path += fptr;
			script_path += ".lua";

			g_modules.push_back(new module(
				mod_path.c_str(),
				init_script_path.c_str(),
				script_path.c_str(),
				lj_alloc_f,
				NULL));
		}

		++offset;
		if(offset == mf)
			break;
	}

	return 1;
}

PLUGIN_API void	XPluginStop(void)
{
	if(g_is_acf_inited)
	{
		for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
			(*m)->acf_unload();
		g_is_acf_inited = 0;
	}

	for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
		delete (*m);
	g_modules.clear();

	xlua_dref_cleanup();
	xlua_cmd_cleanup();
	xlua_timer_cleanup();

	XPLMDestroyFlightLoop(g_pre_loop);
	XPLMDestroyFlightLoop(g_post_loop);
	g_pre_loop = NULL;
	g_post_loop = NULL;
	g_is_acf_inited = 0;
}

PLUGIN_API void XPluginDisable(void)
{
}

PLUGIN_API int XPluginEnable(void)
{
	xlua_relink_all_drefs();
	return 1;
}

PLUGIN_API void XPluginReceiveMessage(
					XPLMPluginID	inFromWho,
					int				inMessage,
					void *			inParam)
{
	if(inFromWho != XPLM_PLUGIN_XPLANE)
		return;

	switch(inMessage) {
	case XPLM_MSG_PLANE_LOADED:
		if(inParam == 0)
			g_is_acf_inited = 0;
		break;
	case XPLM_MSG_PLANE_UNLOADED:
		if(g_is_acf_inited)
		for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
			(*m)->acf_unload();
		g_is_acf_inited = 0;
		break;
	case XPLM_MSG_AIRPORT_LOADED:
		if(!g_is_acf_inited)
		{
			// Pick up any last stragglers from out-of-order load and then validate our datarefs!
			xlua_relink_all_drefs();
			xlua_validate_drefs();

			for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
				(*m)->acf_load();
			g_is_acf_inited = 1;
		}
		for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
			(*m)->flight_init();
		break;
	case XPLM_MSG_PLANE_CRASHED:
		assert(g_is_acf_inited);
		for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
			(*m)->flight_crash();
		break;
	}
}

<commit_msg>XPD-11583 : After-physics callback was being run before<commit_after>//	Copyright 2016, Laminar Research
//	This source code is licensed under the MIT open source license.
//	See LICENSE.txt for the full terms of the license.

#define VERSION "1.1.0r1"

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <vector>

#ifndef XPLM200
#define XPLM200
#endif

#ifndef XPLM210
#define XPLM210
#endif

#include <XPLMPlugin.h>
#include <XPLMDataAccess.h>
#include <XPLMUtilities.h>
#include <XPLMProcessing.h>

#include "module.h"
#include "xpdatarefs.h"
#include "xpcommands.h"
#include "xptimers.h"

using std::vector;

/*

	TODO: get good errors on compile error.
	TODO: pipe output somewhere useful.

 */

extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}

static vector<module *>g_modules;
static XPLMFlightLoopID	g_pre_loop = NULL;
static XPLMFlightLoopID	g_post_loop = NULL;
static int				g_is_acf_inited = 0;
XPLMDataRef				g_replay_active = NULL;
XPLMDataRef				g_sim_period = NULL;

struct lua_alloc_request_t {
			void *	ud;
			void *	ptr;
			size_t	osize;
			size_t	nsize;
};

#define		ALLOC_OPEN		0x00A110C1
#define		ALLOC_REALLOC	0x00A110C2
#define		ALLOC_CLOSE		0x00A110C3
#define		ALLOC_LOCK		0x00A110C4
#define		ALLOC_UNLOCK	0x00A110C5

static void lua_lock()
{
	XPLMSendMessageToPlugin(XPLM_PLUGIN_XPLANE, ALLOC_LOCK, NULL);
}
static void lua_unlock()
{
	XPLMSendMessageToPlugin(XPLM_PLUGIN_XPLANE, ALLOC_UNLOCK, NULL);
}

static void *lj_alloc_create(void)
{
	struct lua_alloc_request_t r = { 0 };
	XPLMSendMessageToPlugin(XPLM_PLUGIN_XPLANE, ALLOC_OPEN,&r);
	return r.ud;
}

static void  lj_alloc_destroy(void *msp)
{
	struct lua_alloc_request_t r = { 0 };
	r.ud = msp;
	XPLMSendMessageToPlugin(XPLM_PLUGIN_XPLANE, ALLOC_CLOSE,&r);
}

static void *lj_alloc_f(void *msp, void *ptr, size_t osize, size_t nsize)
{
	struct lua_alloc_request_t r = { 0 };
	r.ud = msp;
	r.ptr = ptr;
	r.osize = osize;
	r.nsize = nsize;
	XPLMSendMessageToPlugin(XPLM_PLUGIN_XPLANE, ALLOC_REALLOC,&r);
	return r.ptr;
}

static float xlua_pre_timer_master_cb(
                                   float                inElapsedSinceLastCall,
                                   float                inElapsedTimeSinceLastFlightLoop,
                                   int                  inCounter,
                                   void *               inRefcon)
{
	xlua_do_timers_for_time(xlua_get_simulated_time());

	if(XPLMGetDatai(g_replay_active) == 0)
	if(XPLMGetDataf(g_sim_period) > 0.0f)
	for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
		(*m)->pre_physics();
	return -1;
}

static float xlua_post_timer_master_cb(
                                   float                inElapsedSinceLastCall,
                                   float                inElapsedTimeSinceLastFlightLoop,
                                   int                  inCounter,
                                   void *               inRefcon)
{
	if(XPLMGetDatai(g_replay_active) == 0)
	{
		if(XPLMGetDataf(g_sim_period) > 0.0f)
		for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
			(*m)->post_physics();
	}
	else
	for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
		(*m)->post_replay();
	return -1;
}

PLUGIN_API int XPluginStart(
						char *		outName,
						char *		outSig,
						char *		outDesc)
{

    strcpy(outName, "XLua " VERSION);
    strcpy(outSig, "com.x-plane.xlua." VERSION);
    strcpy(outDesc, "A minimal scripting environment for aircraft authors.");

	g_replay_active = XPLMFindDataRef("sim/time/is_in_replay");
	g_sim_period = XPLMFindDataRef("sim/operation/misc/frame_rate_period");

	XPLMCreateFlightLoop_t pre = { 0 };
	XPLMCreateFlightLoop_t post = { 0 };
	pre.structSize = sizeof(pre);
	post.structSize = sizeof(post);
	pre.phase = xplm_FlightLoop_Phase_BeforeFlightModel;
	post.phase = xplm_FlightLoop_Phase_AfterFlightModel;
	pre.callbackFunc = xlua_pre_timer_master_cb;
	post.callbackFunc = xlua_post_timer_master_cb;

	g_pre_loop = XPLMCreateFlightLoop(&pre);
	g_post_loop = XPLMCreateFlightLoop(&post);
	XPLMScheduleFlightLoop(g_pre_loop, -1, 0);
	XPLMScheduleFlightLoop(g_post_loop, -1, 0);

	XPLMEnableFeature("XPLM_USE_NATIVE_PATHS", 1);

	char path_to_me_c[2048];
	XPLMGetPluginInfo(XPLMGetMyID(), NULL, path_to_me_c, NULL, NULL);

	// Plugin base path: pop off two dirs from the plugin name to get the base path.
	string plugin_base_path(path_to_me_c);
	string::size_type lp = plugin_base_path.find_last_of("/\\");
	plugin_base_path.erase(lp);
	lp = plugin_base_path.find_last_of("/\\");
	plugin_base_path.erase(lp+1);

	string init_script_path(plugin_base_path);
	init_script_path += "init.lua";
	string scripts_dir_path(plugin_base_path);

	scripts_dir_path += "scripts";

	int offset = 0;
	int mf, fcount;
	while(1)
	{
		char fname_buf[2048];
		char * fptr;
		XPLMGetDirectoryContents(
								scripts_dir_path.c_str(),
								offset,
								fname_buf,
								sizeof(fname_buf),
								&fptr,
								1,
								&mf,
								&fcount);
		if(fcount == 0)
			break;

		if(strcmp(fptr, ".DS_Store") != 0)
		{
			string mod_path(scripts_dir_path);
			mod_path += "/";
			mod_path += fptr;
			mod_path += "/";
			string script_path(mod_path);
			script_path += fptr;
			script_path += ".lua";

			g_modules.push_back(new module(
				mod_path.c_str(),
				init_script_path.c_str(),
				script_path.c_str(),
				lj_alloc_f,
				NULL));
		}

		++offset;
		if(offset == mf)
			break;
	}

	return 1;
}

PLUGIN_API void	XPluginStop(void)
{
	if(g_is_acf_inited)
	{
		for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
			(*m)->acf_unload();
		g_is_acf_inited = 0;
	}

	for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
		delete (*m);
	g_modules.clear();

	xlua_dref_cleanup();
	xlua_cmd_cleanup();
	xlua_timer_cleanup();

	XPLMDestroyFlightLoop(g_pre_loop);
	XPLMDestroyFlightLoop(g_post_loop);
	g_pre_loop = NULL;
	g_post_loop = NULL;
	g_is_acf_inited = 0;
}

PLUGIN_API void XPluginDisable(void)
{
}

PLUGIN_API int XPluginEnable(void)
{
	xlua_relink_all_drefs();
	return 1;
}

PLUGIN_API void XPluginReceiveMessage(
					XPLMPluginID	inFromWho,
					int				inMessage,
					void *			inParam)
{
	if(inFromWho != XPLM_PLUGIN_XPLANE)
		return;

	switch(inMessage) {
	case XPLM_MSG_PLANE_LOADED:
		if(inParam == 0)
			g_is_acf_inited = 0;
		break;
	case XPLM_MSG_PLANE_UNLOADED:
		if(g_is_acf_inited)
		for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
			(*m)->acf_unload();
		g_is_acf_inited = 0;
		break;
	case XPLM_MSG_AIRPORT_LOADED:
		if(!g_is_acf_inited)
		{
			// Pick up any last stragglers from out-of-order load and then validate our datarefs!
			xlua_relink_all_drefs();
			xlua_validate_drefs();

			for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
				(*m)->acf_load();
			g_is_acf_inited = 1;
		}
		for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
			(*m)->flight_init();
		break;
	case XPLM_MSG_PLANE_CRASHED:
		assert(g_is_acf_inited);
		for(vector<module *>::iterator m = g_modules.begin(); m != g_modules.end(); ++m)
			(*m)->flight_crash();
		break;
	}
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: Os2Transferable.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-09-20 16:39:31 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _DTRANS_OS2_TRANSFERABLE_HXX_
#define _DTRANS_OS2_TRANSFERABLE_HXX_

#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_
#include <com/sun/star/datatransfer/XTransferable.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HDL_
#include <com/sun/star/lang/XEventListener.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif

#include <errno.h>

#include <uclip.h>

#define CHAR_POINTER(THE_OUSTRING) ::rtl::OUStringToOString (THE_OUSTRING, RTL_TEXTENCODING_UTF8).pData->buffer

#if OSL_DEBUG_LEVEL>0
extern "C" int debug_printf(const char *f, ...);
#else
#define debug_printf( ...) { 1; }
#endif

#define CPPUTYPE_SEQSALINT8       getCppuType( (const Sequence< sal_Int8 >*) 0 )
#define CPPUTYPE_DEFAULT          CPPUTYPE_SEQSALINT8

#ifdef OOO_VENDOR
using namespace com::sun::star::uno;
HBITMAP OOoBmpToOS2Handle( Any &aAnyB);
int OS2HandleToOOoBmp( HBITMAP hbm, Sequence< sal_Int8 >* winDIBStream);
#else
#define OOoBmpToOS2Handle(a)    0
#define OS2HandleToOOoBmp(a,b)  0
#endif

namespace os2 {

    class Os2Transferable : public ::cppu::WeakImplHelper1 <
        ::com::sun::star::datatransfer::XTransferable >
    {
        HAB         hAB;
        ::rtl::OUString clipText;
        ::com::sun::star::datatransfer::DataFlavor aFlavor;
        ::osl::Mutex m_aMutex;
        ::com::sun::star::uno::Reference< XInterface >          m_xCreator;

    public:
        Os2Transferable( const ::com::sun::star::uno::Reference< XInterface >& xCreator);
        virtual ~Os2Transferable();

        /*
         * XTransferable
         */

        virtual ::com::sun::star::uno::Any SAL_CALL getTransferData( const ::com::sun::star::datatransfer::DataFlavor& aFlavor )
            throw(::com::sun::star::datatransfer::UnsupportedFlavorException,
                  ::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException
                  );

        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::datatransfer::DataFlavor > SAL_CALL getTransferDataFlavors(  )
            throw(::com::sun::star::uno::RuntimeException);

        virtual sal_Bool SAL_CALL isDataFlavorSupported( const ::com::sun::star::datatransfer::DataFlavor& aFlavor )
            throw(::com::sun::star::uno::RuntimeException);
    };

} // namespace

#endif

<commit_msg>INTEGRATION: CWS os2port02 (1.2.2); FILE MERGED 2007/09/29 16:38:05 ydario 1.2.2.1: Issue number: i82034 Submitted by: ydario Reviewed by:  ydario Commit of changes for OS/2 CWS source code integration.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: Os2Transferable.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 13:15:31 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _DTRANS_OS2_TRANSFERABLE_HXX_
#define _DTRANS_OS2_TRANSFERABLE_HXX_

#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_
#include <com/sun/star/datatransfer/XTransferable.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HDL_
#include <com/sun/star/lang/XEventListener.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif

#include <errno.h>

#include <uclip.h>

#define CHAR_POINTER(THE_OUSTRING) ::rtl::OUStringToOString (THE_OUSTRING, RTL_TEXTENCODING_UTF8).pData->buffer

#if OSL_DEBUG_LEVEL>1
extern "C" int debug_printf(const char *f, ...);
#else
#define debug_printf( ...) { 1; }
#endif

#define CPPUTYPE_SEQSALINT8       getCppuType( (const Sequence< sal_Int8 >*) 0 )
#define CPPUTYPE_DEFAULT          CPPUTYPE_SEQSALINT8

#ifdef OOO_VENDOR
using namespace com::sun::star::uno;
HBITMAP OOoBmpToOS2Handle( Any &aAnyB);
int OS2HandleToOOoBmp( HBITMAP hbm, Sequence< sal_Int8 >* winDIBStream);
#else
#define OOoBmpToOS2Handle(a)    0
#define OS2HandleToOOoBmp(a,b)  0
#endif

namespace os2 {

    class Os2Transferable : public ::cppu::WeakImplHelper1 <
        ::com::sun::star::datatransfer::XTransferable >
    {
        HAB         hAB;
        ::rtl::OUString clipText;
        ::com::sun::star::datatransfer::DataFlavor aFlavor;
        ::osl::Mutex m_aMutex;
        ::com::sun::star::uno::Reference< XInterface >          m_xCreator;

    public:
        Os2Transferable( const ::com::sun::star::uno::Reference< XInterface >& xCreator);
        virtual ~Os2Transferable();

        /*
         * XTransferable
         */

        virtual ::com::sun::star::uno::Any SAL_CALL getTransferData( const ::com::sun::star::datatransfer::DataFlavor& aFlavor )
            throw(::com::sun::star::datatransfer::UnsupportedFlavorException,
                  ::com::sun::star::io::IOException,
                  ::com::sun::star::uno::RuntimeException
                  );

        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::datatransfer::DataFlavor > SAL_CALL getTransferDataFlavors(  )
            throw(::com::sun::star::uno::RuntimeException);

        virtual sal_Bool SAL_CALL isDataFlavorSupported( const ::com::sun::star::datatransfer::DataFlavor& aFlavor )
            throw(::com::sun::star::uno::RuntimeException);
    };

} // namespace

#endif

<|endoftext|>


<commit_before>#include "KWiFi.h"
#include "KEvent.h"
#include <Adafruit_WINC1500.h>
#include <Arduino.h>
#include <string.h>

Adafruit_WINC1500 WiFi(WINC_CS, WINC_IRQ, WINC_RST);
char *KWiFi::ssid = NULL;
char *KWiFi::pass = NULL;

KWiFi::KWiFi(char *s, char *p) : KTask(5000) {
    ssid = s;
    pass = p;
}

#ifdef KWIFI_SERIAL_STATUS

void on_wifi_disconnect(KEvent event, void *callbackData) {
    Serial.println("WiFi disconnected.");
};

void on_wifi_connect(KEvent event, void *callbackData) {
    Serial.println("WiFi connected.");
};

void on_wifi_failed(KEvent event, void *callbackData) {
    Serial.println("WiFi connect failed.");
};

void on_wifi_connecting(KEvent event, void *callbackData) {
    Serial.println("WiFi attempting to connect...");
};
#endif

void KWiFi::init() {
#ifdef WINC_EN
    pinMode(WINC_EN, OUTPUT);
    digitalWrite(WINC_EN, HIGH);
#endif

#ifdef KWIFI_SERIAL_STATUS
    KEvent::on(KEVENT_WIFI_CONNECT, on_wifi_connect, this);
    KEvent::on(KEVENT_WIFI_CONNECTING, on_wifi_connecting, this);
    KEvent::on(KEVENT_WIFI_CONNECT_FAILED, on_wifi_failed, this);
    KEvent::on(KEVENT_WIFI_DISCONNECT, on_wifi_disconnect, this);
#endif
}

void KWiFi::run() {
//    Serial.print("connected=");
//    Serial.print(connected);
//    Serial.print(" connecting=");
//    Serial.print(connecting);
//    Serial.print(" status=");
//    Serial.println(WiFi.status());

    if (WiFi.status() != WL_NO_SHIELD) {
        // attempt to connect to Wifi network:
        if (connected && WiFi.status() != WL_CONNECTED) {
            KEvent::emit(KEVENT_WIFI_DISCONNECT, NULL);
        }
        if (connecting && WiFi.status() == WL_CONNECTED) {
            KEvent::emit(KEVENT_WIFI_CONNECT, NULL);
        }
        if (connecting && WiFi.status() == WL_CONNECT_FAILED) {
            connecting = false;
            KEvent::emit(KEVENT_WIFI_CONNECT_FAILED, NULL);
        }
        connected = WiFi.status() == WL_CONNECTED;
        if (!connecting && !connected) {
            connecting = true;
            connected = false;
            KEvent::emit(KEVENT_WIFI_CONNECTING, NULL);
            WiFi.begin(ssid, pass);
        }
    }
}
<commit_msg>fixed some generic global names<commit_after>#include "KWiFi.h"
#include "KEvent.h"
#include <Adafruit_WINC1500.h>
#include <Arduino.h>
#include <string.h>

Adafruit_WINC1500 WiFi(WINC_CS, WINC_IRQ, WINC_RST);
char *KWiFi::ssid = NULL;
char *KWiFi::pass = NULL;

KWiFi::KWiFi(char *s, char *p) : KTask(5000) {
    ssid = s;
    pass = p;
}

#ifdef KWIFI_SERIAL_STATUS

void KEvent_on_wifi_disconnect(KEvent event, void *callbackData) {
    Serial.println("WiFi disconnected.");
};

void KEvent_on_wifi_connect(KEvent event, void *callbackData) {
    Serial.println("WiFi connected.");
};

void KEvent_on_wifi_failed(KEvent event, void *callbackData) {
    Serial.println("WiFi connect failed.");
};

void KEvent_on_wifi_connecting(KEvent event, void *callbackData) {
    Serial.println("WiFi attempting to connect...");
};
#endif

void KWiFi::init() {
#ifdef WINC_EN
    pinMode(WINC_EN, OUTPUT);
    digitalWrite(WINC_EN, HIGH);
#endif

#ifdef KWIFI_SERIAL_STATUS
    KEvent::on(KEVENT_WIFI_CONNECT, KEvent_on_wifi_connect, this);
    KEvent::on(KEVENT_WIFI_CONNECTING, KEvent_on_wifi_connecting, this);
    KEvent::on(KEVENT_WIFI_CONNECT_FAILED, KEvent_on_wifi_failed, this);
    KEvent::on(KEVENT_WIFI_DISCONNECT, KEvent_on_wifi_disconnect, this);
#endif
}

void KWiFi::run() {
//    Serial.print("connected=");
//    Serial.print(connected);
//    Serial.print(" connecting=");
//    Serial.print(connecting);
//    Serial.print(" status=");
//    Serial.println(WiFi.status());

    if (WiFi.status() != WL_NO_SHIELD) {
        // attempt to connect to Wifi network:
        if (connected && WiFi.status() != WL_CONNECTED) {
            KEvent::emit(KEVENT_WIFI_DISCONNECT, NULL);
        }
        if (connecting && WiFi.status() == WL_CONNECTED) {
            KEvent::emit(KEVENT_WIFI_CONNECT, NULL);
        }
        if (connecting && WiFi.status() == WL_CONNECT_FAILED) {
            connecting = false;
            KEvent::emit(KEVENT_WIFI_CONNECT_FAILED, NULL);
        }
        connected = WiFi.status() == WL_CONNECTED;
        if (!connecting && !connected) {
            connecting = true;
            connected = false;
            KEvent::emit(KEVENT_WIFI_CONNECTING, NULL);
            WiFi.begin(ssid, pass);
        }
    }
}
<|endoftext|>


<commit_before>/***************************************************************************
COSC 501
Elliott Plack
Lab 10
6 NOV 2013                                                  Due 11 NOV 2013
Problem:	Use a class to calculate price-change percentage of a given
			stock, like Google (GOOG)
Algorithm:
***************************************************************************/

#include <iostream>
#include <string>
using namespace std;

class Stock
{
	string symbol;
	string name;
	int previousClosingPrice;
	int currentPrice;
public:
	Stock (string,string,double,double); // constructor
	int readPrice(int,int);
	float changePercent() {return ((currentPrice-previousClosingPrice)/previousClosingPrice);}
};

Stock::Stock(string a, string b,double c,double d)
	{
		symbol = a;
		name = b;
		previousClosingPrice = c;
		currentPrice = d;
	}

int main()
	{
		string symbol, name;
		int previousClosingPrice, currentPrice;

		cout << "Enter the stock symbol: ";
		cin >> symbol;
		cout << "Enter the stock name: ";
		cin >> name;
		cout << "Enter the previous price: ";
		cin >> previousClosingPrice;
		cout << "Enter the current price: ";
		cin >> currentPrice;

		Stock go(symbol,name,previousClosingPrice,currentPrice);

		return 0;
	}

// example: class constructor
<commit_msg>class rewritten<commit_after>/***************************************************************************
COSC 501
Elliott Plack
Lab 10
6 NOV 2013                                                  Due 11 NOV 2013
Problem:	Use a class to calculate price-change percentage of a given
			stock, like Google (GOOG)
Algorithm:
***************************************************************************/

#include <iostream>
#include <string>
using namespace std;

class Stock
{
public:
	Stock(); // default constructor
	Stock (string,string,double,double); // constructor
	~Stock(); // destructor

	string getSymbol() const;
	string getName() const;
	double getPCP() const; //PCP = Previous Closing Price
	double getCP() const;

private:
	string symbol;
	string name;
	double previousClosingPrice;
	double currentPrice;

};
Stock::Stock()
{
	currentPrice = 0;
	previousClosingPrice = 0;
}

Stock::Stock(string symbolInput, string nameInput, double previousClosingPriceInput, double currentPriceInput)
	{
		symbol = symbolInput;
		name = nameInput;
		previousClosingPrice = previousClosingPriceInput;
		currentPrice = currentPriceInput;
	}

Stock::~Stock()
	{

	}

string Stock::getSymbol() const
{
	return symbol;
}

string Stock::getName() const
{
	return name;
}

double Stock::getPCP() const
{
	return previousClosingPrice;
}

double Stock::getCP() const
{
	return currentPrice;
}

int main()
	{
		string symbolInput, nameInput;
		int previousClosingPriceInput, currentPriceInput;

		cout << "Enter the stock symbol: ";
		cin >> symbolInput;
		cout << "Enter the stock name: ";
		cin >> nameInput;
		cout << "Enter the previous price: ";
		cin >> previousClosingPriceInput;
		cout << "Enter the current price: ";
		cin >> currentPriceInput;

		return 0;
	}

// example: class constructor
<|endoftext|>