<commit_before>//=======================================================================
// Copyright (c) 2013-2017 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef MONEY_H
#define MONEY_H

#include <string>
#include <ostream>

#include "utils.hpp"

namespace budget {

constexpr const int SCALE = 100;

struct money {
    long value;

    money() : value(0) {
        //Nothing to init
    }

    money(int dollars, int cents) : value(dollars * SCALE + cents) {
        //Nothing to init
    }

    money operator+(const money& rhs) const {
        money new_money = *this;
        new_money.value += rhs.value;
        return new_money;
    }

    money& operator+=(const money& rhs){
        value += rhs.value;
        return *this;
    }

    money operator-(const money& rhs) const {
        money new_money = *this;
        new_money.value -= rhs.value;
        return new_money;
    }

    money& operator-=(const money& rhs){
        value -= rhs.value;
        return *this;
    }

    money operator*(double factor) const {
        money new_money = *this;
        new_money.value *= factor;
        return new_money;
    }

    money& operator*=(double factor){
        value *= factor;
        return *this;
    }

    money operator*(int factor) const {
        money new_money = *this;
        new_money.value *= factor;
        return new_money;
    }

    money& operator*=(int factor){
        value *= factor;
        return *this;
    }

    money operator/(int factor) const {
        money new_money = *this;
        new_money.value /= factor;
        return new_money;
    }

    money& operator/=(int factor){
        value /= factor;
        return *this;
    }

    bool operator==(const budget::money& rhs) const {
        return value == rhs.value;
    }

    bool operator!=(const budget::money& rhs) const {
        return value != rhs.value;
    }

    bool operator<(const budget::money& rhs) const {
        return value < rhs.value;
    }

    bool operator<=(const budget::money& rhs) const {
        return value < rhs.value;
    }

    bool operator>(const budget::money& rhs) const {
        return value > rhs.value;
    }

    bool operator>=(const budget::money& rhs) const {
        return value >= rhs.value;
    }

    int cents() const {
        return std::abs(value % SCALE);
    }

    int dollars() const {
        return value / SCALE;
    }

    bool positive() const {
        return value > 0;
    }

    bool negative() const {
        return value < 0;
    }

    bool zero() const {
        return value == 0;
    }
};

std::ostream& operator<<(std::ostream& stream, const money& amount);

money parse_money(const std::string& money_string);

money random_money(size_t min, size_t max);

std::string random_name(size_t length);

template<>
inline std::string to_string(money amount){
    std::stringstream stream;
    stream << amount;
    return stream.str();
}

template<typename InputIt, typename Functor>
inline budget::money accumulate_amount_if(InputIt first, InputIt last, Functor f){
    budget::money init;

    for (; first != last; ++first) {
        if(f(*first)){
            init = init + first->amount;
        }
    }

    return init;
}

template<typename T, typename Functor>
inline budget::money accumulate_amount_if(std::vector<T>& container, Functor f){
    return accumulate_amount_if(container.begin(), container.end(), f);
}

} //end of namespace budget

#endif
<commit_msg>Add budget::money(int)<commit_after>//=======================================================================
// Copyright (c) 2013-2017 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef MONEY_H
#define MONEY_H

#include <string>
#include <ostream>

#include "utils.hpp"

namespace budget {

constexpr const int SCALE = 100;

struct money {
    long value;

    money() : value(0) {
        //Nothing to init
    }

    explicit money(int dollars) : value(dollars * SCALE) {
        //Nothing to init
    }

    money(int dollars, int cents) : value(dollars * SCALE + cents) {
        //Nothing to init
    }

    money operator+(const money& rhs) const {
        money new_money = *this;
        new_money.value += rhs.value;
        return new_money;
    }

    money& operator+=(const money& rhs){
        value += rhs.value;
        return *this;
    }

    money operator-(const money& rhs) const {
        money new_money = *this;
        new_money.value -= rhs.value;
        return new_money;
    }

    money& operator-=(const money& rhs){
        value -= rhs.value;
        return *this;
    }

    money operator*(double factor) const {
        money new_money = *this;
        new_money.value *= factor;
        return new_money;
    }

    money& operator*=(double factor){
        value *= factor;
        return *this;
    }

    money operator*(int factor) const {
        money new_money = *this;
        new_money.value *= factor;
        return new_money;
    }

    money& operator*=(int factor){
        value *= factor;
        return *this;
    }

    money operator/(int factor) const {
        money new_money = *this;
        new_money.value /= factor;
        return new_money;
    }

    money& operator/=(int factor){
        value /= factor;
        return *this;
    }

    bool operator==(const budget::money& rhs) const {
        return value == rhs.value;
    }

    bool operator!=(const budget::money& rhs) const {
        return value != rhs.value;
    }

    bool operator<(const budget::money& rhs) const {
        return value < rhs.value;
    }

    bool operator<=(const budget::money& rhs) const {
        return value < rhs.value;
    }

    bool operator>(const budget::money& rhs) const {
        return value > rhs.value;
    }

    bool operator>=(const budget::money& rhs) const {
        return value >= rhs.value;
    }

    int cents() const {
        return std::abs(value % SCALE);
    }

    int dollars() const {
        return value / SCALE;
    }

    bool positive() const {
        return value > 0;
    }

    bool negative() const {
        return value < 0;
    }

    bool zero() const {
        return value == 0;
    }
};

std::ostream& operator<<(std::ostream& stream, const money& amount);

money parse_money(const std::string& money_string);

money random_money(size_t min, size_t max);

std::string random_name(size_t length);

template<>
inline std::string to_string(money amount){
    std::stringstream stream;
    stream << amount;
    return stream.str();
}

template<typename InputIt, typename Functor>
inline budget::money accumulate_amount_if(InputIt first, InputIt last, Functor f){
    budget::money init;

    for (; first != last; ++first) {
        if(f(*first)){
            init = init + first->amount;
        }
    }

    return init;
}

template<typename T, typename Functor>
inline budget::money accumulate_amount_if(std::vector<T>& container, Functor f){
    return accumulate_amount_if(container.begin(), container.end(), f);
}

} //end of namespace budget

#endif
<|endoftext|>


<commit_before>// sersim
//
// 	simulate the Serial library in Arduinosville

#include <iostream>
#include "sersim.h"

sersim::sersim( void )
{
}

sersim::~sersim( void )
{
}

bool sersim::operator!( void )
{
	return false;
}

void sersim::begin( long speed, long config )
{
	std::cout << "Begin Serial" << std::endl;
}

void sersim::end( void )
{
	std::cout << "Close Serial" << std::endl;
}

int sersim::available( void )
{
	 // returns number of bytes to read
	return 0;
}

int sersim::peek( void )
{
	return 0;
}

#ifndef BIN
#define BIN	(1)
#define OCT	(8)
#define DEC	(10)
#define HEX	(16)
#endif

void sersim::print( long v, int fmt ) // BIN, OCT, DEC, HEX
{
}

void sersim::print( double v, int prec ) // bits of precision after decimal point
{
}

void sersim::print( std::string v )
{
}

void sersim::println( long v, int fmt ) // BIN, OCT, DEC, HEX
{
	this->print( v, fmt );
	this->print( "\n" );
}

void sersim::println( double v, int prec ) // bits of precision after decimal point
{
	this->print( v, prec );
	this->print( "\n" );
}

void sersim::println( std::string v )
{
	this->print( v );
	this->print( "\n" );
}

void sersim::write( long v )
{
}

void sersim::write( std::string v )
{
}

void sersim::write( char * v, long len )
{
}

void sersim::flush( void )
{
	std::cout << std::flush;
}

int sersim::read( void )
{
	return 0;
}

sersim Serial;
<commit_msg>Basic Serial output simulation<commit_after>// sersim
//
// 	simulate the Serial library in Arduinosville

#include <iostream>
#include "sersim.h"

sersim::sersim( void )
{
}

sersim::~sersim( void )
{
}

bool sersim::operator!( void )
{
	return false;
}

void sersim::begin( long speed, long config )
{
	std::cout << "Begin Serial" << std::endl;
}

void sersim::end( void )
{
	std::cout << "Close Serial" << std::endl;
}

int sersim::available( void )
{
	 // returns number of bytes to read
	return 0;
}

int sersim::peek( void )
{
	return 0;
}

#ifndef BIN
#define BIN	(1)
#define OCT	(8)
#define DEC	(10)
#define HEX	(16)
#endif

void sersim::print( long v, int fmt ) // BIN, OCT, DEC, HEX
{
	char buf[ 128 ];
	int p=0;

	switch( fmt ) {
	case( BIN ):
		int bit;
		for( bit = 0x80 ; bit>0 ; bit>>=1 );
		{
			buf[p] = (v&bit)?'1':'0';
			p++;
		}
		buf[p] = '\0';
		break;

	case( OCT ):
		snprintf( buf, 128, "%lo", v );
		break;

	case( HEX ):
		snprintf( buf, 128, "%02lx", v );
		break;

	case( DEC ):
	default:
		snprintf( buf, 128, "%ld", v );
		break;
	}

	std::cout << buf << std::flush;
}

void sersim::print( double v, int prec ) // bits of precision after decimal point
{
	char buf[128];
	char fmt[128];
	snprintf( fmt, 128, "%%0.%df", prec );
	snprintf( buf, 128, fmt, v );
	std::cout << buf << std::flush;
}

void sersim::print( std::string v )
{
	std::cout << v << std::flush;
}

void sersim::println( long v, int fmt ) // BIN, OCT, DEC, HEX
{
	this->print( v, fmt );
	this->print( "\n" );
}

void sersim::println( double v, int prec ) // bits of precision after decimal point
{
	this->print( v, prec );
	this->print( "\n" );
}

void sersim::println( std::string v )
{
	this->print( v );
	this->print( "\n" );
}

void sersim::write( long v )
{
	unsigned char buf[ 3 ];
	buf[0] = (unsigned char) (v & 0x00ff);
	buf[1] = '\0';
	std::cout << buf << std::flush;
}

void sersim::write( std::string v )
{
	std::cout << v << std::flush;
}

void sersim::write( char * v, long len )
{
	if( !v ) return;

	for( int a=0 ; a<len ; a++ )
	{
		std::cout << v[a];
	}
	std::cout << std::flush;
}

void sersim::flush( void )
{
	std::cout << std::flush;
}

int sersim::read( void )
{
	return 0;
}

sersim Serial;
<|endoftext|>


<commit_before>/*
 * Joey Button
 *
 *
 */

#include <stdio.h>
#include <opencv2/video/background_segm.hpp>
#include "opencv2/opencv.hpp"

// #include <iostream>
// #include <sstream>

using namespace cv;
using namespace std;
#define RADIUS 32

Mat fgMaskMOG; //fg mask generated by MOG method

BackgroundSubtractorMOG2 MOG;

const char *win = "video";

void drawCircle(Mat img, Point center)
{
    int thickness = -1;
    int lineType = 8;

    circle( img,
            center,
            RADIUS,
            Scalar( 255, 255, 255 ),
            thickness,
            lineType);
}

void calcDir(Point *momentum, Point *pt, int height, int width){
      pt->x += momentum->x;
      pt->y += momentum->y;

      if (pt->y < height) {
           // Accelerate due to Gravity
          momentum->y += 1;
      } else {
          momentum->x = momentum->x *0.9;
          momentum->y = -(momentum->y * .5);   // bounce back up and halt it
          pt->y = height;
      }

      //off the top
      if (pt->y < RADIUS) {
            pt->y=RADIUS;
            momentum->y += 1;
            momentum->y = -(momentum->y * .5);
            momentum->x = momentum->x *0.9;
      }

      if (momentum->y * momentum->y <= 49 && pt->y > height){
          momentum->y = 0;
      }

}

int main()
{
    int cam = 0; // default camera
    VideoCapture cap(cam);
    if (!cap.isOpened()) {
        fprintf(stderr, "cannot open camera %d\n", cam);
        exit(1);
    }

    // namedWindow(win);
    namedWindow(win, 1);
    Mat inputFrame, outFrame;
    Point pt;
    pt.x = 500;
    pt.y = 0;

    Point momentum;
    momentum.x = 0;
    momentum.y = 150;

    double count = 0;

    cap >> inputFrame;
    cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);

    int height = inputFrame.rows-2*RADIUS;
    int width = inputFrame.cols-2*RADIUS;

    while (++count) {
        cap >> inputFrame;

        calcDir(&momentum, &pt, height, width);

        MOG(inputFrame, fgMaskMOG);

        //EVERYTHING ABOVE THIS SHOULD BE CALCULATING WHERE TO DRAW

        //EVERYTHING BELOW THIS LINE SHOULD BE DRAWING THE outFrame
        outFrame.setTo(Scalar(0,0,0)); //set all of outFrame to be black

        drawCircle(fgMaskMOG,pt);//for testing
        imshow(win, fgMaskMOG);//for testing

        // drawCircle(outFrame,pt);//The real one
        // imshow(win, outFrame);//The real one

        if (waitKey(1) >= 0) // wait up to 30 msec
	        break;
    }

    return 0;
}

/*
    Mat BGRChannels[3];
    split(outFrame,BGRChannels); // split the BGR channesl
    BGRChannels[1]=Mat::zeros(outFrame.rows,outFrame.cols,CV_8UC1);// removing Green channel
    merge(BGRChannels,3,outFrame); // pack the image

    waitKey(0);
*/
<commit_msg>working, kinda<commit_after>/*
 * Joey Button
 *
 *
 */

#include <stdio.h>
#include <opencv2/video/background_segm.hpp>
#include "opencv2/opencv.hpp"

// #include <iostream>
// #include <sstream>

using namespace cv;
using namespace std;
#define RADIUS 32

const char *win = "video";

void drawCircle(Mat img, Point center)
{
    int thickness = -1;
    int lineType = 8;

    circle( img,
            center,
            RADIUS,
            Scalar( 255, 255, 255 ),
            thickness,
            lineType);
}

void calcDir(Point *momentum, Point *pt, int height, int width){
      pt->x += momentum->x;
      pt->y += momentum->y;

      if (pt->y < height) {
           // Accelerate due to Gravity
          momentum->y += 1;
      } else {
          momentum->x = momentum->x *0.9;
          momentum->y = -(momentum->y * .5);   // bounce back up and halt it
          pt->y = height;
      }

      //off the top
      if (pt->y < RADIUS) {
            pt->y=RADIUS;
            momentum->y += 1;
            momentum->y = -(momentum->y * .5);
            momentum->x = momentum->x *0.9;
      }

      if (momentum->y * momentum->y <= 49 && pt->y > height){
          momentum->y = 0;
      }

}

int main()
{
    int cam = 0; // default camera
    VideoCapture cap(cam);
    if (!cap.isOpened()) {
        fprintf(stderr, "cannot open camera %d\n", cam);
        exit(1);
    }

    namedWindow(win, CV_WINDOW_AUTOSIZE);

    Mat fgMaskMOG; //fg mask generated by MOG method
    Mat inputFrame, outFrame;
    Mat circ;
    Point pt;

    BackgroundSubtractorMOG2 MOG;

    pt.x = 500;
    pt.y = 0;

    Point momentum;
    momentum.x = 0;
    momentum.y = 150;

    double count = 0;

    cap >> inputFrame;
    cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);
    cvtColor(inputFrame, circ, CV_BGR2GRAY);

    int height = inputFrame.rows-2*RADIUS;
    int width = inputFrame.cols-2*RADIUS;

    while (++count) {
        cap >> inputFrame;

        calcDir(&momentum, &pt, height, width);

        MOG(inputFrame, fgMaskMOG);

        circ.setTo(Scalar(0,0,0));
        drawCircle(circ,pt);//for testing

        bitwise_and(circ, fgMaskMOG, circ);//THIS IS FOR CALCULATING INTERSECTION
        //anything white, in circ, is intersecting the ball to be drawn --
        //Change the momentum here

        if ( sum(circ)[0] > 10000.0)
          momentum.y -= 10;

        //EVERYTHING ABOVE THIS SHOULD BE CALCULATING WHERE TO DRAW

        //EVERYTHING BELOW THIS LINE SHOULD BE DRAWING THE outFrame
        outFrame.setTo(Scalar(0,0,0)); //set all of outFrame to be black

        drawCircle(fgMaskMOG,pt);//for testing
        imshow(win, fgMaskMOG);//for testing

        // drawCircle(outFrame,pt);//The real one
        // imshow(win, outFrame);//The real one

        if (waitKey(1) >= 0) // wait up to 30 msec
	        break;
    }

    return 0;
}

/*
    Mat BGRChannels[3];
    split(outFrame,BGRChannels); // split the BGR channesl
    BGRChannels[1]=Mat::zeros(outFrame.rows,outFrame.cols,CV_8UC1);// removing Green channel
    merge(BGRChannels,3,outFrame); // pack the image

    waitKey(0);
*/
<|endoftext|>


<commit_before>/*
 * HyPerLayer.hpp
 *
 *  Created on: Aug 3, 2008
 *      Author: dcoates
 *
 *  The top of the hierarchy for layer classes.
 *
 *  To make it easy to subclass from classes in the HyPerLayer hierarchy,
 *  please follow the guidelines below when adding subclasses to the HyPerLayer hierarchy:
 *
 *  For a class named DerivedLayer that is derived from a class named BaseLayer,
 *  the .hpp file should have
namespace PV {
class DerivedLayer : public BaseLayer {
public:
  DerivedLayer(arguments); // The constructor called by
  // other methods
protected:
  DerivedLayer();
  int initialize(arguments);
  // other methods and member variables
private:
  int initialize_base();
  // other methods and member variables
};
}
 *
 * The .cpp file should have
namespace PV {
DerivedLayer::DerivedLayer() {
  initialize_base();
  // initialize(arguments) should *not* be called by the protected constructor.
}
DerivedLayer::DerivedLayer(arguments, generally includes the layer's name and the parent HyPerCol) {
  initialize_base();
  initialize(arguments);
}
DerivedLayer::initialize_base() {
  // the most basic initializations.  Don't call any virtual methods,
  // or methods that call virtual methods, etc. from initialize_base();
}
DerivedLayer::initialize(arguments) {
  // DerivedLayer-specific initializations that need to precede BaseClass initialization, if any
  BaseClass::initialize(BaseClass initialization arguments);
  // DerivedLayer-specific initializations
}

  // other DerivedLayer methods
}
 */

#ifndef HYPERLAYER_HPP_
#define HYPERLAYER_HPP_

#include "../layers/PVLayer.h"
#include "../layers/LayerDataInterface.hpp"
#include "../columns/DataStore.hpp"
#include "../columns/HyPerCol.hpp"
#include "../columns/InterColComm.hpp"
#include "../io/LayerProbe.hpp"
#include "../include/pv_common.h"
#include "../include/pv_types.h"
#include "../utils/Timer.hpp"

#ifndef PV_USE_OPENCL
#  include "../layers/updateStateFunctions.h"
#else
#  undef PV_USE_OPENCL
#  include "../layers/updateStateFunctions.h"
#  define PV_USE_OPENCL
#endif

#ifdef PV_USE_OPENCL
#define PV_CL_COPY_BUFFERS 0
#define PV_CL_EVENTS 1
#include "../arch/opencl/CLKernel.hpp"
#define EV_GSYN 0
#define EV_ACTIVITY 1
#define EV_HPL_PHI_E 0
#define EV_HPL_PHI_I 1
#endif

namespace PV {

class InitV;

class HyPerLayer : public LayerDataInterface {

protected:

   // only subclasses can be constructed directly
   HyPerLayer();
   int initialize(const char * name, HyPerCol * hc, int numChannels);

   virtual int initializeLayerId(int layerId);
   int setLayerLoc(PVLayerLoc * layerLoc, float nxScale, float nyScale, int margin, int nf);
   virtual int allocateBuffers();
   static int readBufferFile(const char * filename, InterColComm * comm, double * timed, pvdata_t * buffer, int numbands, bool extended, bool contiguous, const PVLayerLoc * loc);
   int readDataStoreFromFile(const char * filename, InterColComm * comm, double * timed);
   static int readHeader(const char * filename, InterColComm * comm, double * timed, int * params, const PVLayerLoc * loc);
   static int writeBufferFile(const char * filename, InterColComm * comm, double dtime, pvdata_t * buffer, int numbands, bool extended, bool contiguous, const PVLayerLoc * loc);
   static int writeBuffer(FILE * fp, InterColComm * comm, double dtime, pvdata_t * buffer, int numbands, bool extended, bool contiguous, const PVLayerLoc * loc);
   int incrementNBands(int * numCalls);
   int writeDataStoreToFile(const char * filename, InterColComm * comm, double dtime);
   virtual int calcActiveIndices();
   int readScalarFloat(const char * cp_dir, const char * val_name, float * val_ptr, float default_value=0.0f);
   int writeScalarFloat(const char * cp_dir, const char * val_name, float value);

#ifdef PV_USE_OPENCL
   virtual int initializeThreadBuffers(const char * kernelName);
   virtual int initializeThreadKernels(const char * kernelName);
#endif

private:
   int initialize_base();

public:

   virtual ~HyPerLayer() = 0;
   virtual int initializeState();

   static int copyToBuffer(pvdata_t * buf, const pvdata_t * data,
                           const PVLayerLoc * loc, bool extended, float scale);
   static int copyToBuffer(unsigned char * buf, const pvdata_t * data,
                           const PVLayerLoc * loc, bool extended, float scale);

   template <typename T>
   static int copyFromBuffer(const T * buf, T * data,
                             const PVLayerLoc * loc, bool extended, T scale);

   static int copyFromBuffer(const unsigned char * buf, pvdata_t * data,
                             const PVLayerLoc * loc, bool extended, float scale);

   // TODO - make protected
   PVLayer  * clayer;

   virtual int triggerReceive(InterColComm * comm);
   virtual int recvSynapticInput(HyPerConn * conn, const PVLayerCube * cube, int arborID);
   virtual int updateState (float time, float dt);
   virtual int updateBorder(float time, float dt);
   virtual int publish(InterColComm * comm, float time);
   virtual int waitOnPublish(InterColComm * comm);

   virtual int updateActiveIndices();
   int resetBuffer(pvdata_t * buf, int numItems);

   virtual int reconstruct(HyPerConn * conn, PVLayerCube * cube);

   int initFinish();

   int mirrorInteriorToBorder(int whichBorder, PVLayerCube * cube, PVLayerCube * borderCube);

   virtual int columnWillAddLayer(InterColComm * comm, int id);

   virtual int checkpointRead(const char * cpDir, float * timef);
   virtual int checkpointWrite(const char * cpDir);

   virtual int readState (float * timef);
#ifdef OBSOLETE // Marked obsolete July 13, 2012.  Dumping the state is now done by checkpointWrite.
   virtual int writeState(float timef, bool last=false);
#endif // OBSOLETE
   virtual int outputState(float timef, bool last=false);
   virtual int writeActivity(float timef);
   virtual int writeActivitySparse(float timef);

   virtual int insertProbe(LayerProbe * probe);

   /** returns the number of neurons in layer (for borderId=0) or a border region **/
   virtual int numberOfNeurons(int borderId);

   virtual int mirrorToNorthWest(PVLayerCube * dest, PVLayerCube * src);
   virtual int mirrorToNorth    (PVLayerCube * dest, PVLayerCube* src);
   virtual int mirrorToNorthEast(PVLayerCube * dest, PVLayerCube * src);
   virtual int mirrorToWest     (PVLayerCube * dest, PVLayerCube * src);
   virtual int mirrorToEast     (PVLayerCube * dest, PVLayerCube * src);
   virtual int mirrorToSouthWest(PVLayerCube * dest, PVLayerCube * src);
   virtual int mirrorToSouth    (PVLayerCube * dest, PVLayerCube * src);
   virtual int mirrorToSouthEast(PVLayerCube * dest, PVLayerCube * src);

   const char * getOutputFilename(char * buf, const char * dataName, const char * term);

   // Public access functions:

   const char * getName()            {return name;}

   int getNumNeurons()               {return clayer->numNeurons;}
   int getNumExtended()              {return clayer->numExtended;}
   int getNumGlobalNeurons()         {const PVLayerLoc * loc = getLayerLoc(); return loc->nxGlobal*loc->nyGlobal*loc->nf;}
   int getNumGlobalExtended()        {const PVLayerLoc * loc = getLayerLoc(); return (loc->nxGlobal+2*loc->nb)*(loc->nyGlobal+2*loc->nb)*loc->nf;}

   int  getLayerId()                 {return clayer->layerId;}
   PVLayerType getLayerType()        {return clayer->layerType;}
   void setLayerId(int id)           {clayer->layerId = id;}
   int increaseDelayLevels(int neededDelay);

   PVLayer*  getCLayer()             {return clayer;}
   pvdata_t * getV()                 {return clayer->V;}           // name query
   pvdata_t * getActivity()          {return clayer->activity->data;}
   int getNumChannels()              {return numChannels;}
   pvdata_t * getChannel(ChannelType ch) {                         // name query
      return ch < this->numChannels ? GSyn[ch] : NULL;
   }
   int getXScale()                   {return clayer->xScale;}
   int getYScale()                   {return clayer->yScale;}

   HyPerCol* getParent()             {return parent;}
   void setParent(HyPerCol* parent)  {this->parent = parent;}

   bool useMirrorBCs()               {return this->mirrorBCflag;}
   bool getSpikingFlag()             {return this->spikingFlag;}

   // implementation of LayerDataInterface interface
   //
   const pvdata_t   * getLayerData(int delay=0);
   const PVLayerLoc * getLayerLoc()  { return &(clayer->loc); }
   bool isExtended()                 { return true; }

   virtual int gatherToInteriorBuffer(unsigned char * buf);

   virtual int label(int k);

   virtual int * getMarginIndices();
   virtual int getNumMargin();

protected:

   /* static */ int updateState(float timef, float dt, const PVLayerLoc * loc, pvdata_t * A, pvdata_t * V, int num_channels, pvdata_t * GSynHead, bool spiking, unsigned int * active_indices, unsigned int * num_active);
   virtual int setActivity();
   void freeChannels();

   HyPerCol * parent;

   char * name;                 // well known name of layer

   int numChannels;             // number of channels
   pvdata_t ** GSyn;            // of dynamic length numChannels

   int numProbes;
   LayerProbe ** probes;

   int * labels;                // label for the feature a neuron is tuned to

   bool mirrorBCflag;           // true when mirror BC are to be applied

   int ioAppend;                // controls opening of binary files
   float writeTime;             // time of next output
   float writeStep;             // output time interval

   bool spikingFlag;
   bool writeNonspikingActivity;
   int writeActivityCalls;      // Number of calls to writeActivity (written to nbands in the header of the a%d.pvp file)
   int writeActivitySparseCalls; // Number of calls to writeActivitySparse (written to nbands in the header of the a%d.pvp file)

   int * marginIndices;   // indices of neurons in margin
   int numMargin;         // number of neurons in margin

   // OpenCL variables
   //
#ifdef PV_USE_OPENCL
public:
   int initializeGPU(); //this method setups up GPU stuff...
   //virtual int getNumCLEvents() {return 0;}
   virtual const char * getKernelName() {return NULL;}
   virtual int getNumKernelArgs() {return numKernelArgs;}
   virtual int getNumCLEvents()   {return numEvents;}

   CLBuffer * getChannelCLBuffer() {
      return clGSyn;
   }
//   CLBuffer * getChannelCLBuffer(ChannelType ch) {
//      return ch < this->numChannels ? clGSyn[ch] : NULL;
//   }
   //#define EV_PHI_E 0
   //#define EV_PHI_I 1
   virtual int getEVGSyn() {return EV_GSYN;}
   virtual int getEVGSynE() {return EV_HPL_PHI_E;}
   virtual int getEVGSynI() {return EV_HPL_PHI_I;}
   virtual int getEVActivity() {return EV_ACTIVITY;}
   CLBuffer * getLayerDataStoreCLBuffer();
   size_t     getLayerDataStoreOffset(int delay=0);
   void initUseGPUFlag();
   inline bool getUseGPUFlag() {return gpuAccelerateFlag;}
   //int initializeDataStoreThreadBuffers();
   inline bool getCopyDataStoreFlag() {return copyDataStoreFlag;}
   int waitForDataStoreCopy();
   int copyDataStoreCLBuffer();
   void tellLayerToCopyDataStoreCLBuffer(/*cl_event * evCpDataStore*/) {copyDataStoreFlag=true; /*evCopyDataStore=evCpDataStore;*/}

   //temporary method for debuging recievesynapticinput
   virtual inline int getGSynEvent(ChannelType ch) {
      switch (ch) {
      case CHANNEL_EXC: return getEVGSynE();
      case CHANNEL_INH: return getEVGSynI();
      default: return -1;
      }
   }
   virtual void copyGSynFromDevice() {
      int gsynEvent = getEVGSyn();
//      if(numWait>0) {
//         clWaitForEvents(numWait, &evList[gsynEvent]);
//         for (int i = 0; i < numWait; i++) {
//            clReleaseEvent(evList[i]);
//         }
//         numWait = 0;
//      }
      if(gsynEvent>=0){
         clGSyn->copyFromDevice(&evList[gsynEvent]);
         clWaitForEvents(1, &evList[gsynEvent]);
         clReleaseEvent(evList[gsynEvent]);
      }
   }
//   virtual void copyChannelFromDevice(ChannelType ch) {
//      int gsynEvent = getGSynEvent(ch);
//      if(gsynEvent>=0){
//         getChannelCLBuffer(ch)->copyFromDevice(&evList[gsynEvent]);
//         clWaitForEvents(1, &evList[gsynEvent]);
//         clReleaseEvent(evList[gsynEvent]);
//      }
//   }
   virtual void copyGSynToDevice() {
      int gsynEvent = getEVGSyn();
      if(gsynEvent>=0){
         clGSyn->copyToDevice(&evList[gsynEvent]);
         clWaitForEvents(1, &evList[gsynEvent]);
         clReleaseEvent(evList[gsynEvent]);
      }
      //copyToDevice=true;
   }
   void startTimer() {recvsyn_timer->start();}
   void stopTimer() {recvsyn_timer->stop();}

protected:

   CLKernel * krUpdate;        // CL kernel for update state call

   // OpenCL buffers
   //
   CLBuffer * clV;
   //CLBuffer **clGSyn;         // of dynamic length numChannels
   CLBuffer * clGSyn;         // of dynamic length numChannels
   CLBuffer * clActivity;
   CLBuffer * clPrevTime;
   CLBuffer * clParams;       // for transferring params to kernel

   int numKernelArgs;         // number of arguments in kernel call
   int numEvents;             // number of events in event list
   int numWait;               // number of events to wait for
   cl_event * evList;         // event list
   cl_event   evUpdate;
   //cl_event * evCopyDataStore;

   int nxl;  // local OpenCL grid size in x
   int nyl;  // local OpenCL grid size in y

   bool gpuAccelerateFlag;
   //bool copyToDevice;
   bool copyDataStoreFlag;
   //bool buffersInitialized;

#endif

   Timer * update_timer;
   Timer * recvsyn_timer;
};

} // namespace PV

// Template functions
//
template <typename T>
int PV::HyPerLayer::copyFromBuffer(const T * buf, T * data,
                                   const PVLayerLoc * loc, bool extended, T scale)
{
   size_t sf, sx, sy;

   const int nx = loc->nx;
   const int ny = loc->ny;
   const int nf = loc->nf;

   int nxBorder = 0;
   int nyBorder = 0;

   if (extended) {
      nxBorder = loc->nb;
      nyBorder = loc->nb;
      sf = strideFExtended(loc);
      sx = strideXExtended(loc);
      sy = strideYExtended(loc);
   }
   else {
      sf = strideF(loc);
      sx = strideX(loc);
      sy = strideY(loc);
   }

   int ii = 0;
   for (int j = 0; j < ny; j++) {
      int jex = j + nyBorder;
      for (int i = 0; i < nx; i++) {
         int iex = i + nxBorder;
         for (int f = 0; f < nf; f++) {
            data[iex*sx + jex*sy + f*sf] = scale * buf[ii++];
         }
      }
   }
   return 0;
}

#endif /* HYPERLAYER_HPP_ */
<commit_msg>HyPerLayer::readBufferFile and writeBufferFile made public so that connections can use them if they have layer-like buffers that need to be checkpointed<commit_after>/*
 * HyPerLayer.hpp
 *
 *  Created on: Aug 3, 2008
 *      Author: dcoates
 *
 *  The top of the hierarchy for layer classes.
 *
 *  To make it easy to subclass from classes in the HyPerLayer hierarchy,
 *  please follow the guidelines below when adding subclasses to the HyPerLayer hierarchy:
 *
 *  For a class named DerivedLayer that is derived from a class named BaseLayer,
 *  the .hpp file should have
namespace PV {
class DerivedLayer : public BaseLayer {
public:
  DerivedLayer(arguments); // The constructor called by
  // other methods
protected:
  DerivedLayer();
  int initialize(arguments);
  // other methods and member variables
private:
  int initialize_base();
  // other methods and member variables
};
}
 *
 * The .cpp file should have
namespace PV {
DerivedLayer::DerivedLayer() {
  initialize_base();
  // initialize(arguments) should *not* be called by the protected constructor.
}
DerivedLayer::DerivedLayer(arguments, generally includes the layer's name and the parent HyPerCol) {
  initialize_base();
  initialize(arguments);
}
DerivedLayer::initialize_base() {
  // the most basic initializations.  Don't call any virtual methods,
  // or methods that call virtual methods, etc. from initialize_base();
}
DerivedLayer::initialize(arguments) {
  // DerivedLayer-specific initializations that need to precede BaseClass initialization, if any
  BaseClass::initialize(BaseClass initialization arguments);
  // DerivedLayer-specific initializations
}

  // other DerivedLayer methods
}
 */

#ifndef HYPERLAYER_HPP_
#define HYPERLAYER_HPP_

#include "../layers/PVLayer.h"
#include "../layers/LayerDataInterface.hpp"
#include "../columns/DataStore.hpp"
#include "../columns/HyPerCol.hpp"
#include "../columns/InterColComm.hpp"
#include "../io/LayerProbe.hpp"
#include "../include/pv_common.h"
#include "../include/pv_types.h"
#include "../utils/Timer.hpp"

#ifndef PV_USE_OPENCL
#  include "../layers/updateStateFunctions.h"
#else
#  undef PV_USE_OPENCL
#  include "../layers/updateStateFunctions.h"
#  define PV_USE_OPENCL
#endif

#ifdef PV_USE_OPENCL
#define PV_CL_COPY_BUFFERS 0
#define PV_CL_EVENTS 1
#include "../arch/opencl/CLKernel.hpp"
#define EV_GSYN 0
#define EV_ACTIVITY 1
#define EV_HPL_PHI_E 0
#define EV_HPL_PHI_I 1
#endif

namespace PV {

class InitV;

class HyPerLayer : public LayerDataInterface {

protected:

   // only subclasses can be constructed directly
   HyPerLayer();
   int initialize(const char * name, HyPerCol * hc, int numChannels);

   virtual int initializeLayerId(int layerId);
   int setLayerLoc(PVLayerLoc * layerLoc, float nxScale, float nyScale, int margin, int nf);
   virtual int allocateBuffers();
   int readDataStoreFromFile(const char * filename, InterColComm * comm, double * timed);
   static int readHeader(const char * filename, InterColComm * comm, double * timed, int * params, const PVLayerLoc * loc);
   static int writeBuffer(FILE * fp, InterColComm * comm, double dtime, pvdata_t * buffer, int numbands, bool extended, bool contiguous, const PVLayerLoc * loc);
   int incrementNBands(int * numCalls);
   int writeDataStoreToFile(const char * filename, InterColComm * comm, double dtime);
   virtual int calcActiveIndices();
   int readScalarFloat(const char * cp_dir, const char * val_name, float * val_ptr, float default_value=0.0f);
   int writeScalarFloat(const char * cp_dir, const char * val_name, float value);

#ifdef PV_USE_OPENCL
   virtual int initializeThreadBuffers(const char * kernelName);
   virtual int initializeThreadKernels(const char * kernelName);
#endif

private:
   int initialize_base();

public:

   virtual ~HyPerLayer() = 0;
   virtual int initializeState();

   static int copyToBuffer(pvdata_t * buf, const pvdata_t * data,
                           const PVLayerLoc * loc, bool extended, float scale);
   static int copyToBuffer(unsigned char * buf, const pvdata_t * data,
                           const PVLayerLoc * loc, bool extended, float scale);

   template <typename T>
   static int copyFromBuffer(const T * buf, T * data,
                             const PVLayerLoc * loc, bool extended, T scale);

   static int copyFromBuffer(const unsigned char * buf, pvdata_t * data,
                             const PVLayerLoc * loc, bool extended, float scale);

   // TODO - make protected
   PVLayer  * clayer;

   virtual int triggerReceive(InterColComm * comm);
   virtual int recvSynapticInput(HyPerConn * conn, const PVLayerCube * cube, int arborID);
   virtual int updateState (float time, float dt);
   virtual int updateBorder(float time, float dt);
   virtual int publish(InterColComm * comm, float time);
   virtual int waitOnPublish(InterColComm * comm);

   virtual int updateActiveIndices();
   int resetBuffer(pvdata_t * buf, int numItems);

   virtual int reconstruct(HyPerConn * conn, PVLayerCube * cube);

   int initFinish();

   int mirrorInteriorToBorder(int whichBorder, PVLayerCube * cube, PVLayerCube * borderCube);

   virtual int columnWillAddLayer(InterColComm * comm, int id);

   virtual int checkpointRead(const char * cpDir, float * timef);
   virtual int checkpointWrite(const char * cpDir);
   static int readBufferFile(const char * filename, InterColComm * comm, double * timed, pvdata_t * buffer, int numbands, bool extended, bool contiguous, const PVLayerLoc * loc);
   static int writeBufferFile(const char * filename, InterColComm * comm, double dtime, pvdata_t * buffer, int numbands, bool extended, bool contiguous, const PVLayerLoc * loc);

   virtual int readState (float * timef);
#ifdef OBSOLETE // Marked obsolete July 13, 2012.  Dumping the state is now done by checkpointWrite.
   virtual int writeState(float timef, bool last=false);
#endif // OBSOLETE
   virtual int outputState(float timef, bool last=false);
   virtual int writeActivity(float timef);
   virtual int writeActivitySparse(float timef);

   virtual int insertProbe(LayerProbe * probe);

   /** returns the number of neurons in layer (for borderId=0) or a border region **/
   virtual int numberOfNeurons(int borderId);

   virtual int mirrorToNorthWest(PVLayerCube * dest, PVLayerCube * src);
   virtual int mirrorToNorth    (PVLayerCube * dest, PVLayerCube* src);
   virtual int mirrorToNorthEast(PVLayerCube * dest, PVLayerCube * src);
   virtual int mirrorToWest     (PVLayerCube * dest, PVLayerCube * src);
   virtual int mirrorToEast     (PVLayerCube * dest, PVLayerCube * src);
   virtual int mirrorToSouthWest(PVLayerCube * dest, PVLayerCube * src);
   virtual int mirrorToSouth    (PVLayerCube * dest, PVLayerCube * src);
   virtual int mirrorToSouthEast(PVLayerCube * dest, PVLayerCube * src);

   const char * getOutputFilename(char * buf, const char * dataName, const char * term);

   // Public access functions:

   const char * getName()            {return name;}

   int getNumNeurons()               {return clayer->numNeurons;}
   int getNumExtended()              {return clayer->numExtended;}
   int getNumGlobalNeurons()         {const PVLayerLoc * loc = getLayerLoc(); return loc->nxGlobal*loc->nyGlobal*loc->nf;}
   int getNumGlobalExtended()        {const PVLayerLoc * loc = getLayerLoc(); return (loc->nxGlobal+2*loc->nb)*(loc->nyGlobal+2*loc->nb)*loc->nf;}

   int  getLayerId()                 {return clayer->layerId;}
   PVLayerType getLayerType()        {return clayer->layerType;}
   void setLayerId(int id)           {clayer->layerId = id;}
   int increaseDelayLevels(int neededDelay);

   PVLayer*  getCLayer()             {return clayer;}
   pvdata_t * getV()                 {return clayer->V;}           // name query
   pvdata_t * getActivity()          {return clayer->activity->data;}
   int getNumChannels()              {return numChannels;}
   pvdata_t * getChannel(ChannelType ch) {                         // name query
      return ch < this->numChannels ? GSyn[ch] : NULL;
   }
   int getXScale()                   {return clayer->xScale;}
   int getYScale()                   {return clayer->yScale;}

   HyPerCol* getParent()             {return parent;}
   void setParent(HyPerCol* parent)  {this->parent = parent;}

   bool useMirrorBCs()               {return this->mirrorBCflag;}
   bool getSpikingFlag()             {return this->spikingFlag;}

   // implementation of LayerDataInterface interface
   //
   const pvdata_t   * getLayerData(int delay=0);
   const PVLayerLoc * getLayerLoc()  { return &(clayer->loc); }
   bool isExtended()                 { return true; }

   virtual int gatherToInteriorBuffer(unsigned char * buf);

   virtual int label(int k);

   virtual int * getMarginIndices();
   virtual int getNumMargin();

protected:

   /* static */ int updateState(float timef, float dt, const PVLayerLoc * loc, pvdata_t * A, pvdata_t * V, int num_channels, pvdata_t * GSynHead, bool spiking, unsigned int * active_indices, unsigned int * num_active);
   virtual int setActivity();
   void freeChannels();

   HyPerCol * parent;

   char * name;                 // well known name of layer

   int numChannels;             // number of channels
   pvdata_t ** GSyn;            // of dynamic length numChannels

   int numProbes;
   LayerProbe ** probes;

   int * labels;                // label for the feature a neuron is tuned to

   bool mirrorBCflag;           // true when mirror BC are to be applied

   int ioAppend;                // controls opening of binary files
   float writeTime;             // time of next output
   float writeStep;             // output time interval

   bool spikingFlag;
   bool writeNonspikingActivity;
   int writeActivityCalls;      // Number of calls to writeActivity (written to nbands in the header of the a%d.pvp file)
   int writeActivitySparseCalls; // Number of calls to writeActivitySparse (written to nbands in the header of the a%d.pvp file)

   int * marginIndices;   // indices of neurons in margin
   int numMargin;         // number of neurons in margin

   // OpenCL variables
   //
#ifdef PV_USE_OPENCL
public:
   int initializeGPU(); //this method setups up GPU stuff...
   //virtual int getNumCLEvents() {return 0;}
   virtual const char * getKernelName() {return NULL;}
   virtual int getNumKernelArgs() {return numKernelArgs;}
   virtual int getNumCLEvents()   {return numEvents;}

   CLBuffer * getChannelCLBuffer() {
      return clGSyn;
   }
//   CLBuffer * getChannelCLBuffer(ChannelType ch) {
//      return ch < this->numChannels ? clGSyn[ch] : NULL;
//   }
   //#define EV_PHI_E 0
   //#define EV_PHI_I 1
   virtual int getEVGSyn() {return EV_GSYN;}
   virtual int getEVGSynE() {return EV_HPL_PHI_E;}
   virtual int getEVGSynI() {return EV_HPL_PHI_I;}
   virtual int getEVActivity() {return EV_ACTIVITY;}
   CLBuffer * getLayerDataStoreCLBuffer();
   size_t     getLayerDataStoreOffset(int delay=0);
   void initUseGPUFlag();
   inline bool getUseGPUFlag() {return gpuAccelerateFlag;}
   //int initializeDataStoreThreadBuffers();
   inline bool getCopyDataStoreFlag() {return copyDataStoreFlag;}
   int waitForDataStoreCopy();
   int copyDataStoreCLBuffer();
   void tellLayerToCopyDataStoreCLBuffer(/*cl_event * evCpDataStore*/) {copyDataStoreFlag=true; /*evCopyDataStore=evCpDataStore;*/}

   //temporary method for debuging recievesynapticinput
   virtual inline int getGSynEvent(ChannelType ch) {
      switch (ch) {
      case CHANNEL_EXC: return getEVGSynE();
      case CHANNEL_INH: return getEVGSynI();
      default: return -1;
      }
   }
   virtual void copyGSynFromDevice() {
      int gsynEvent = getEVGSyn();
//      if(numWait>0) {
//         clWaitForEvents(numWait, &evList[gsynEvent]);
//         for (int i = 0; i < numWait; i++) {
//            clReleaseEvent(evList[i]);
//         }
//         numWait = 0;
//      }
      if(gsynEvent>=0){
         clGSyn->copyFromDevice(&evList[gsynEvent]);
         clWaitForEvents(1, &evList[gsynEvent]);
         clReleaseEvent(evList[gsynEvent]);
      }
   }
//   virtual void copyChannelFromDevice(ChannelType ch) {
//      int gsynEvent = getGSynEvent(ch);
//      if(gsynEvent>=0){
//         getChannelCLBuffer(ch)->copyFromDevice(&evList[gsynEvent]);
//         clWaitForEvents(1, &evList[gsynEvent]);
//         clReleaseEvent(evList[gsynEvent]);
//      }
//   }
   virtual void copyGSynToDevice() {
      int gsynEvent = getEVGSyn();
      if(gsynEvent>=0){
         clGSyn->copyToDevice(&evList[gsynEvent]);
         clWaitForEvents(1, &evList[gsynEvent]);
         clReleaseEvent(evList[gsynEvent]);
      }
      //copyToDevice=true;
   }
   void startTimer() {recvsyn_timer->start();}
   void stopTimer() {recvsyn_timer->stop();}

protected:

   CLKernel * krUpdate;        // CL kernel for update state call

   // OpenCL buffers
   //
   CLBuffer * clV;
   //CLBuffer **clGSyn;         // of dynamic length numChannels
   CLBuffer * clGSyn;         // of dynamic length numChannels
   CLBuffer * clActivity;
   CLBuffer * clPrevTime;
   CLBuffer * clParams;       // for transferring params to kernel

   int numKernelArgs;         // number of arguments in kernel call
   int numEvents;             // number of events in event list
   int numWait;               // number of events to wait for
   cl_event * evList;         // event list
   cl_event   evUpdate;
   //cl_event * evCopyDataStore;

   int nxl;  // local OpenCL grid size in x
   int nyl;  // local OpenCL grid size in y

   bool gpuAccelerateFlag;
   //bool copyToDevice;
   bool copyDataStoreFlag;
   //bool buffersInitialized;

#endif

   Timer * update_timer;
   Timer * recvsyn_timer;
};

} // namespace PV

// Template functions
//
template <typename T>
int PV::HyPerLayer::copyFromBuffer(const T * buf, T * data,
                                   const PVLayerLoc * loc, bool extended, T scale)
{
   size_t sf, sx, sy;

   const int nx = loc->nx;
   const int ny = loc->ny;
   const int nf = loc->nf;

   int nxBorder = 0;
   int nyBorder = 0;

   if (extended) {
      nxBorder = loc->nb;
      nyBorder = loc->nb;
      sf = strideFExtended(loc);
      sx = strideXExtended(loc);
      sy = strideYExtended(loc);
   }
   else {
      sf = strideF(loc);
      sx = strideX(loc);
      sy = strideY(loc);
   }

   int ii = 0;
   for (int j = 0; j < ny; j++) {
      int jex = j + nyBorder;
      for (int i = 0; i < nx; i++) {
         int iex = i + nxBorder;
         for (int f = 0; f < nf; f++) {
            data[iex*sx + jex*sy + f*sf] = scale * buf[ii++];
         }
      }
   }
   return 0;
}

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


<commit_before>/**
 civ_spectra_dataset.cpp
 Purpose: This files contains the body for the functions defined in civ_spectra_dataset.h

 @author Ignasi Pérez-Ràfols
 @version 1.0 08/08/2014
 */

#include "civ_spectra_dataset.h"

CIVSpectraDataset::CIVSpectraDataset(const Input& input){
    /**
     EXPLANATION:
     Cosntructs a CIVSpectraDataset instance and loads a catalog of LyaSpectrum objects into it

     INPUTS:
     input - object of type cInput

     OUTPUTS:
     NONE

     CLASSES USED:
     CIVSpectraDataset
     Input

     FUNCITONS USED:
     NONE
     */

    flag_verbose_civ_spectra_dataset_ = input.flag_verbose_civ_spectra_dataset();
    name_ = input.dataset2_name();
    Load(input.dataset2(), "", input.lya_wl());

}

void CIVSpectraDataset::Load(const std::string& lya_spectra_catalog, const std::string& lya_spectra_dir, const double& lya_wl){
    /**
     EXPLANATION:
     Loads the object dataset from a catalog file

     INPUTS:
     lya_spectra_catalog - a string with the name of the list of fits files containing the spectra
     lya_spectra_dir - a string with the directory where the ly-a spectrum files are stored
     lya_wl - a double with the wavelength of the lyman-alpha line (in Angstroms)

     OUTPUTS:
     NONE

     CLASSES USED:
     LyaSpectrum
     LyaSpectraDataset

     FUNCITONS USED:
     NONE
     */

    if (flag_verbose_civ_spectra_dataset_ >= 1){
        std::cout << "Loading civ spectra dataset" << std::endl;
    }

    // setting the catalog columns to be read
    std::vector<std::string> fields_hdu1(3);
    fields_hdu1[0] = "LOBS";
    fields_hdu1[1] = "DELTA";
    fields_hdu1[2] = "WEIGHT";
    std::vector<std::string> fields_hdu2(6);
    fields_hdu2[0] = "RA";
    fields_hdu2[1] = "DEC";
    fields_hdu2[2] = "Z";
    fields_hdu2[3] = "PLATE";
    fields_hdu2[4] = "MJD";
    fields_hdu2[5] = "FIBER_D";

    // construct fits object
    std::auto_ptr<CCfits::FITS> pInfile;

    try{
        pInfile = std::auto_ptr<CCfits::FITS>(new CCfits::FITS(lya_spectra_catalog,CCfits::Read,true));

    } catch(CCfits::FITS::CantOpen x) {

        throw "Error: in QuasarDataset::Load : Couldn't open catalog file: " + lya_spectra_catalog;
    }
    std::cout << "loading hdu 1\n";
    CCfits::ExtHDU& data_hdu1 = pInfile->extension(1);
    std::cout << "loading hdu 1\n";
    CCfits::ExtHDU& data_hdu2 = pInfile->extension(2);

    // number of lines in the file
    long NAXIS2_HDU1 = data_hdu1.axis(1);
    size_t nobj_hdu1 = NAXIS2_HDU1;
    long NAXIS2_HDU2 = data_hdu2.axis(1);
    size_t nobj_hdu2 = NAXIS2_HDU2;

    // this will store the information
    std::valarray<int> plate, mjd, fiber;
    std::valarray<double> ra, dec, z, lobs, delta, weight;

    // reading data
    std::cout << "reading data from hdu 1\n";
    data_hdu1.column(fields_hdu1[0]).read(lobs,1,nobj_hdu1); // observed wavelength
    data_hdu1.column(fields_hdu1[1]).read(delta,1,nobj_hdu1); // measured overdensity (delta)
    data_hdu1.column(fields_hdu1[2]).read(weight,1,nobj_hdu1); // weight
    std::cout << "reading data from hdu 1\n";
    data_hdu2.column(fields_hdu2[0]).read(ra,1,nobj_hdu2); // ra (in degrees)
    data_hdu2.column(fields_hdu2[1]).read(dec,1,nobj_hdu2); // dec (in degrees)
    data_hdu2.column(fields_hdu2[2]).read(z,1,nobj_hdu2); // z
    data_hdu2.column(fields_hdu2[3]).read(plate,1,nobj_hdu2); // plate
    data_hdu2.column(fields_hdu2[4]).read(mjd,1,nobj_hdu2); // mjd
    data_hdu2.column(fields_hdu2[5]).read(fiber,1,nobj_hdu2); // fiber

    // setting size to zero and creating entries in list_ map
    size_ = 0;
    for (int i = 0; i < nobj_hdu2; i++){

        if (list_.find(plate[i]) == list_.end()){
            std::vector<LyaSpectrum> v;
            list_[plate[i]] = v;
            num_objects_in_plate_[plate[i]] = 0;
        }

    }

    // adding objects to list_ and to list_by_plate
    size_t forest_size = nobj_hdu2/nobj_hdu1;
    std::vector<double> lobs_q(forest_size, 0.0), delta_q(forest_size, 0.0), weight_q(forest_size, 0.0);
    for (int i=0;i<nobj_hdu2;i++){
        if ( not (ra[i] == 0.0 and dec[i] == 0.0)){

            // create LyaSpectrum
            for (int j=0; j < forest_size; j++){
                lobs_q[j] = lobs[i + j];
                delta_q[j] = delta[i + j];
                weight_q[j] = weight[i + j];
            }
            LyaSpectrum object(ra[i], dec[i], plate[i], fiber[i], mjd[i], z[i], lobs_q, delta_q, weight_q, false);

            // adding object to list_
            (*list_.find(plate[i])).second.push_back(object);

            // updating size_
            size_ ++;

            // updating number_of_objects_in_plate
            (*num_objects_in_plate_.find(plate[i])).second ++;

            if (flag_verbose_civ_spectra_dataset_ >= 3 or (flag_verbose_civ_spectra_dataset_ >= 2 and size_ == size_/1000*1000)){
                std::cout << "Loaded " << size_ << " civ spectra" << std::endl;
            }

        }
    }

    if (flag_verbose_civ_spectra_dataset_ >= 1){
        std::cout << "Loaded " << size_ << " civ spectra" << std::endl;
    }

}<commit_msg>civ debuged (2)<commit_after>/**
 civ_spectra_dataset.cpp
 Purpose: This files contains the body for the functions defined in civ_spectra_dataset.h

 @author Ignasi Pérez-Ràfols
 @version 1.0 08/08/2014
 */

#include "civ_spectra_dataset.h"

CIVSpectraDataset::CIVSpectraDataset(const Input& input){
    /**
     EXPLANATION:
     Cosntructs a CIVSpectraDataset instance and loads a catalog of LyaSpectrum objects into it

     INPUTS:
     input - object of type cInput

     OUTPUTS:
     NONE

     CLASSES USED:
     CIVSpectraDataset
     Input

     FUNCITONS USED:
     NONE
     */

    flag_verbose_civ_spectra_dataset_ = input.flag_verbose_civ_spectra_dataset();
    name_ = input.dataset2_name();
    Load(input.dataset2(), "", input.lya_wl());

}

void CIVSpectraDataset::Load(const std::string& lya_spectra_catalog, const std::string& lya_spectra_dir, const double& lya_wl){
    /**
     EXPLANATION:
     Loads the object dataset from a catalog file

     INPUTS:
     lya_spectra_catalog - a string with the name of the list of fits files containing the spectra
     lya_spectra_dir - a string with the directory where the ly-a spectrum files are stored
     lya_wl - a double with the wavelength of the lyman-alpha line (in Angstroms)

     OUTPUTS:
     NONE

     CLASSES USED:
     LyaSpectrum
     LyaSpectraDataset

     FUNCITONS USED:
     NONE
     */

    if (flag_verbose_civ_spectra_dataset_ >= 1){
        std::cout << "Loading civ spectra dataset" << std::endl;
    }

    // setting the catalog columns to be read
    std::vector<std::string> fields(9);
    fields[0] = "LOBS";
    fields[1] = "DELTA";
    fields[2] = "WEIGHT";
    fields[3] = "RA";
    fields[4] = "DEC";
    fields[5] = "Z";
    fields[6] = "PLATE";
    fields[7] = "MJD";
    fields[8] = "FIBER_ID";

    // construct fits object
    std::auto_ptr<CCfits::FITS> pInfile;

    try{

        pInfile = std::auto_ptr<CCfits::FITS>(new CCfits::FITS(civ_filename,CCfits::Read,1,true,fields));

    } catch(CCfits::FITS::CantOpen x) {

        throw "Error: in QuasarDataset::Load : Couldn't open catalog file: " + civ_filename;
    }
    CCfits::ExtHDU& data = pInfile->extension(1);

    // number of lines in the file
    long NAXIS2 = data.axis(1);
    size_t nobj = NAXIS2;

    // this will store the information
    std::valarray<int> plate, mjd, fiber;
    std::valarray<double> ra, dec, z;
    std::vector<std::valarray<double> > lobs, delta, weight;

    // reading data
    data.column(fields[0]).readArrays(lobs, 1, nobj); // observed wavelength
    data.column(fields[1]).readArrays(delta, 1, nobj); // measured overdensities
    data.column(fields[2]).readArrays(weight, 1, nobj); // weights
    data.column(fields[3]).read(ra, 1, nobj); // ra
    data.column(fields[4]).read(dec, 1, nobj); // dec
    data.column(fields[5]).read(z, 1, nobj); // z
    data.column(fields[6]).read(plate, 1, nobj); // plate number
    data.column(fields[7]).read(mjd, 1, nobj); // mjd
    data.column(fields[8]).read(fiber, 1, nobj); // fiber number

    // setting size to zero and creating entries in list_ map
    size_ = 0;
    for (int i = 0; i < nobj; i++){

        if (list_.find(plate[i]) == list_.end()){
            std::vector<LyaSpectrum> v;
            list_[plate[i]] = v;
            num_objects_in_plate_[plate[i]] = 0;
        }

    }

    // adding objects to list_ and to list_by_plate
    for (int i = 0; i < nobj; i++){
        if ( not (ra[i] == 0.0 and dec[i] == 0.0)){

            // create LyaSpectrum
            LyaSpectrum object(ra[i], dec[i], plate[i], fiber[i], mjd[i], z[i], lobs[i], delta[i], weight[i], false);

            // adding object to list_
            (*list_.find(plate[i])).second.push_back(object);

            // updating size_
            size_ ++;

            // updating number_of_objects_in_plate
            (*num_objects_in_plate_.find(plate[i])).second ++;

            if (flag_verbose_civ_spectra_dataset_ >= 3 or (flag_verbose_civ_spectra_dataset_ >= 2 and size_ == size_/1000*1000)){
                std::cout << "Loaded " << size_ << " civ spectra" << std::endl;
            }

        }
    }

    if (flag_verbose_civ_spectra_dataset_ >= 1){
        std::cout << "Loaded " << size_ << " civ spectra" << std::endl;
    }

}<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <set>
#include <thread>

#include "cpp_utils/assert.hpp"

#include "server.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "accounts.hpp"
#include "assets.hpp"
#include "config.hpp"
#include "objectives.hpp"
#include "wishes.hpp"
#include "fortune.hpp"
#include "recurring.hpp"
#include "debts.hpp"
#include "currency.hpp"
#include "server_api.hpp"
#include "server_pages.hpp"
#include "http.hpp"

using namespace budget;

namespace {

bool server_running = false;

void start_server(){
    httplib::Server server;

    load_pages(server);
    load_api(server);

    std::string listen = "localhost";
    size_t port = 8080;

    if(config_contains("server_port")){
        port = to_number<size_t>(config_value("server_port"));
    }

    if(config_contains("server_listen")){
        listen = config_value("server_listen");
    }

    // Listen
    server.listen(listen.c_str(), port);
}

void start_cron_loop(){
    size_t hours = 0;

    while(true){
        using namespace std::chrono_literals;

        std::this_thread::sleep_for(1h);
        ++hours;

        check_for_recurrings();

        if(hours % 72 == 0){
            std::cout << "Refresh the currency cache" << std::endl;
            budget::refresh_currency_cache();
        }
    }
}

} //end of anonymous namespace

void budget::set_server_running(){
    // Indicates to the system that it's running in server mode
    server_running = true;
}

void budget::server_module::load(){
    load_accounts();
    load_expenses();
    load_earnings();
    load_assets();
    load_objectives();
    load_wishes();
    load_fortunes();
    load_recurrings();
    load_debts();
    load_wishes();
}

void budget::server_module::handle(const std::vector<std::string>& args){
    cpp_unused(args);

    std::cout << "Starting the server" << std::endl;

    std::thread server_thread([](){ start_server(); });
    std::thread cron_thread([](){ start_cron_loop(); });

    server_thread.join();
    cron_thread.join();
}

bool budget::is_server_running(){
    return server_running;
}
<commit_msg>Debugging support<commit_after>//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <set>
#include <thread>

#include "cpp_utils/assert.hpp"

#include "server.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "accounts.hpp"
#include "assets.hpp"
#include "config.hpp"
#include "objectives.hpp"
#include "wishes.hpp"
#include "fortune.hpp"
#include "recurring.hpp"
#include "debts.hpp"
#include "currency.hpp"
#include "share.hpp"
#include "server_api.hpp"
#include "server_pages.hpp"
#include "http.hpp"

using namespace budget;

namespace {

bool server_running = false;

void start_server(){
    httplib::Server server;

    load_pages(server);
    load_api(server);

    std::string listen = "localhost";
    size_t port = 8080;

    if(config_contains("server_port")){
        port = to_number<size_t>(config_value("server_port"));
    }

    if(config_contains("server_listen")){
        listen = config_value("server_listen");
    }

    // Listen
    server.listen(listen.c_str(), port);
}

void start_cron_loop(){
    size_t hours = 0;

    std::cout << "Debug: VOO " << budget::share_price("VOO") << std::endl;

    while(true){
        using namespace std::chrono_literals;

        std::this_thread::sleep_for(1h);
        ++hours;

        check_for_recurrings();

        if(hours % 72 == 0){
            std::cout << "Refresh the currency cache" << std::endl;
            budget::refresh_currency_cache();
        }
    }
}

} //end of anonymous namespace

void budget::set_server_running(){
    // Indicates to the system that it's running in server mode
    server_running = true;
}

void budget::server_module::load(){
    load_accounts();
    load_expenses();
    load_earnings();
    load_assets();
    load_objectives();
    load_wishes();
    load_fortunes();
    load_recurrings();
    load_debts();
    load_wishes();
}

void budget::server_module::handle(const std::vector<std::string>& args){
    cpp_unused(args);

    std::cout << "Starting the server" << std::endl;

    std::thread server_thread([](){ start_server(); });
    std::thread cron_thread([](){ start_cron_loop(); });

    server_thread.join();
    cron_thread.join();
}

bool budget::is_server_running(){
    return server_running;
}
<|endoftext|>


<commit_before>
#include "INIParser.h"

INIParser::INIParser(const char * iniFile)
{
  _iniFile = iniFile;
}

int INIParser::parse()
{

  char ch;
  char buffer[100];
  int i = 0;
  int line = 1;

  std::string section = "__NO_SECTION__";
  std::string name;
  parseState = NO_SECTION;

  // open ini file
  std::ifstream in(_iniFile.c_str(), std::ios::in | std::ios::binary);

  while ( in.get(ch) ) {
    switch (ch) {
      case '[' :
	if (isStartSection())
	  return line;

	if ( i == 0 )
	  parseState = START_SECTION;
	else
	  return line;

	break;
      case ']' :
	if (isStopSection())
	  return line;

	if (isStartSection() && i > 0) {
	  buffer[i] = '\0';
	  section = buffer;
	  //std::cout << "section => " << buffer << std::endl;
	  i=0;
	} else { // else error , empty section [] or ] not the end of start section
	  return line;
	}

	parseState = STOP_SECTION;
	break;
      case '=' :

	if ( isStartSection() )
	  return line;

	if ( isNoSection() && i == 0 )
	  return line;

	if ((isNewline() || isNoSection()) && i > 0) {
	  buffer[i] = '\0';
	  name = buffer;
	  //std::cout << "key => " << buffer << std::endl;
	  i=0;
	} else if (isNewline() && i == 0)
	  	return line;

	parseState = DELIMITER;

	break;
      case '\n' :

	if ( isNewline() && i > 0 )
	  return line;

	if ( isNoSection() && i > 0  )
	  return line;

	if ( isStartSection() )
	  return line;

	if ( isDelimiter() && i > 0 ) {
	  buffer[i] = '\0';
	  sections[section][name] = buffer;
	  //std::cout << "value => " << buffer << std::endl;
	  i=0;
	} else if ( isDelimiter() && i == 0 )
		return line;

	//if ( parseState != DELIMITER || parseState != STOP_SECTION || parseState != COMMENT )
	 // return line;

	parseState = NEWLINE;
	line++;
	break;
      case ';' :
	parseState = COMMENT;
	break;
      case '#' :
	parseState = COMMENT;
	break;
      case ' ' :
	break;
      default :

	if ( isNewline() || isNoSection() ) {
	  buffer[i] = ch;
	  i++;
	}

	if ( isDelimiter() ) {
	  buffer[i] = ch;
	  i++;
	}

	if ( isStartSection() ) {
	  buffer[i] = ch;
	  i++;
	}
	// else error

	break;
    }
  }

  in.close();

  return 0;
}

std::string & INIParser::getValue(char * section, char * name)
{
  std::string *value = new std::string("__no_value__");

  Sections::iterator it_s = sections.find(section);

  if ( it_s != sections.end() ) {
    Parameters::iterator it_p =  it_s->second.find(name);
    if ( it_p != it_s->second.end() ) {
      return it_p->second;
    }
  }

  return *value;
}

Parameters & INIParser::getParameters(char * section)
{

  Sections::iterator it_s = sections.find(section);

  if ( it_s != sections.end() ) {

  return sections[section];
}

bool INIParser::isSection(char * section)
{
  return ( sections.count(section) > 0 );
}

bool INIParser::isValue(char * section, char * name)
{
  if ( isSection(section) > 0 )
    if ( sections[section].count(name) > 0 )
      return true;

  return false;
}

bool INIParser::isNoSection()
{
  if ( parseState == NO_SECTION )
    return true;

  return false;
}

bool INIParser::isStartSection()
{
  if ( parseState == START_SECTION )
    return true;

  return false;
}

bool INIParser::isStopSection()
{
  if ( parseState == STOP_SECTION )
    return true;

  return false;
}

bool INIParser::isDelimiter()
{
  if ( parseState == DELIMITER )
    return true;

  return false;
}

bool INIParser::isComment()
{
  if ( parseState == COMMENT )
    return true;

  return false;
}

bool INIParser::isNewline()
{
  if ( parseState == NEWLINE )
    return true;

  return false;
}
<commit_msg>Made it build against as some code was not complete.<commit_after>
#include "INIParser.h"

INIParser::INIParser(const char * iniFile)
{
  _iniFile = iniFile;
}

int INIParser::parse()
{

  char ch;
  char buffer[100];
  int i = 0;
  int line = 1;

  std::string section = "__NO_SECTION__";
  std::string name;
  parseState = NO_SECTION;

  // open ini file
  std::ifstream in(_iniFile.c_str(), std::ios::in | std::ios::binary);

  while ( in.get(ch) ) {
    switch (ch) {
      case '[' :
	if (isStartSection())
	  return line;

	if ( i == 0 )
	  parseState = START_SECTION;
	else
	  return line;

	break;
      case ']' :
	if (isStopSection())
	  return line;

	if (isStartSection() && i > 0) {
	  buffer[i] = '\0';
	  section = buffer;
	  //std::cout << "section => " << buffer << std::endl;
	  i=0;
	} else { // else error , empty section [] or ] not the end of start section
	  return line;
	}

	parseState = STOP_SECTION;
	break;
      case '=' :

	if ( isStartSection() )
	  return line;

	if ( isNoSection() && i == 0 )
	  return line;

	if ((isNewline() || isNoSection()) && i > 0) {
	  buffer[i] = '\0';
	  name = buffer;
	  //std::cout << "key => " << buffer << std::endl;
	  i=0;
	} else if (isNewline() && i == 0)
	  	return line;

	parseState = DELIMITER;

	break;
      case '\n' :

	if ( isNewline() && i > 0 )
	  return line;

	if ( isNoSection() && i > 0  )
	  return line;

	if ( isStartSection() )
	  return line;

	if ( isDelimiter() && i > 0 ) {
	  buffer[i] = '\0';
	  sections[section][name] = buffer;
	  //std::cout << "value => " << buffer << std::endl;
	  i=0;
	} else if ( isDelimiter() && i == 0 )
		return line;

	//if ( parseState != DELIMITER || parseState != STOP_SECTION || parseState != COMMENT )
	 // return line;

	parseState = NEWLINE;
	line++;
	break;
      case ';' :
	parseState = COMMENT;
	break;
      case '#' :
	parseState = COMMENT;
	break;
      case ' ' :
	break;
      default :

	if ( isNewline() || isNoSection() ) {
	  buffer[i] = ch;
	  i++;
	}

	if ( isDelimiter() ) {
	  buffer[i] = ch;
	  i++;
	}

	if ( isStartSection() ) {
	  buffer[i] = ch;
	  i++;
	}
	// else error

	break;
    }
  }

  in.close();

  return 0;
}

std::string & INIParser::getValue(char * section, char * name)
{
  std::string *value = new std::string("__no_value__");

  Sections::iterator it_s = sections.find(section);

  if ( it_s != sections.end() ) {
    Parameters::iterator it_p =  it_s->second.find(name);
    if ( it_p != it_s->second.end() ) {
      return it_p->second;
    }
  }

  return *value;
}

Parameters & INIParser::getParameters(char * section)
{

  Sections::iterator it_s = sections.find(section);

//  if ( it_s != sections.end() ) {

  return sections[section];
}

bool INIParser::isSection(char * section)
{
  return ( sections.count(section) > 0 );
}

bool INIParser::isValue(char * section, char * name)
{
  if ( isSection(section) > 0 )
    if ( sections[section].count(name) > 0 )
      return true;

  return false;
}

bool INIParser::isNoSection()
{
  if ( parseState == NO_SECTION )
    return true;

  return false;
}

bool INIParser::isStartSection()
{
  if ( parseState == START_SECTION )
    return true;

  return false;
}

bool INIParser::isStopSection()
{
  if ( parseState == STOP_SECTION )
    return true;

  return false;
}

bool INIParser::isDelimiter()
{
  if ( parseState == DELIMITER )
    return true;

  return false;
}

bool INIParser::isComment()
{
  if ( parseState == COMMENT )
    return true;

  return false;
}

bool INIParser::isNewline()
{
  if ( parseState == NEWLINE )
    return true;

  return false;
}
<|endoftext|>


<commit_before>#pragma once

#include <algorithm>
#include <cassert>

namespace {
	template <typename T>
	void swapEndian (T* p) {
		uint8_t* q = reinterpret_cast<uint8_t*>(p);

		std::reverse(q, q + sizeof(T));
	}
}

template <typename T>
struct TypedFixedSlice {
protected:
	T* _begin;
	T* _end;

public:
	TypedFixedSlice () : _begin(nullptr), _end(nullptr) {}
	TypedFixedSlice (T* begin, T* end) : _begin(begin), _end(end) {
		assert(this->_begin);
		assert(this->_end);
	}

	auto begin () const { return this->_begin; }
	auto end () const { return this->_end; }

	auto drop (size_t n) const;
	auto take (size_t n) const;

	size_t length () const {
		return static_cast<size_t>(this->_end - this->_begin) / sizeof(T);
	}

	template <typename Y = T>
	auto peek (const size_t offset = 0) const {
		assert(offset + sizeof(Y) <= this->length());
		return *(reinterpret_cast<Y*>(this->_begin + offset));
	}

	template <typename Y, bool swap = false>
	void put (const Y value, size_t offset = 0) {
		assert(offset + sizeof(Y) <= this->length());
		auto ptr = reinterpret_cast<Y*>(this->_begin + offset);
		*ptr = value;

		if (swap) swapEndian(ptr);
	}

	auto& operator[] (const size_t i) {
		assert(i < this->length());
		return this->_begin[i];
	}

	const auto operator[] (const size_t i) const {
		assert(i < this->length());
		return this->_begin[i];
	}

	const auto operator< (const TypedFixedSlice<T>& rhs) const {
		return std::lexicographical_compare(this->_begin, this->_end, rhs._begin, rhs._end);
	}
};

template <typename T>
struct TypedSlice : public TypedFixedSlice<T> {
	TypedSlice () : TypedFixedSlice<T>() {}
	TypedSlice (T* begin, T* end) : TypedFixedSlice<T>(begin, end) {}

	void popFrontN (size_t n) {
		assert(n <= this->length());
		this->_begin += n;
	}

	void popFront () {
		this->popFrontN(1);
	}

	template <typename Y>
	auto read () {
		const auto value = this->template peek<Y>();
		this->popFrontN(sizeof(T) / sizeof(Y));
		return value;
	}

	template <typename Y, bool swap = false>
	void write (const Y value) {
		this->template put<Y, swap>(value);
		this->popFrontN(sizeof(T) / sizeof(Y));
	}

	template <typename Y>
	void writeN (const Y* data, size_t n) {
		assert(n <= this->length());
		memcpy(this->_begin, data, n);
		this->popFrontN(n);
	}
};

template <typename T>
auto TypedFixedSlice<T>::drop (const size_t n) const {
	assert(n <= this->length());
	return TypedSlice<T>(this->_begin + n, this->_end);
}

template <typename T>
auto TypedFixedSlice<T>::take (const size_t n) const {
	assert(n <= this->length());
	return TypedSlice<T>(this->_begin, this->_begin + n);
}

template <typename T, size_t N>
struct TypedStackSlice : TypedFixedSlice<T> {
private:
	T data[N];

public:
	TypedStackSlice () : TypedFixedSlice<T>(data, data + N) {}
// 	TypedStackSlice (const TypedStackSlice& copy) {
// 		memcpy(this->_begin, copy._begin, N);
// 	}
};

template <typename T>
struct TypedHeapSlice : TypedFixedSlice<T> {
	TypedHeapSlice (const size_t n) : TypedFixedSlice<T>() {
		this->_begin = new T[n];
		this->_end = this->_begin + n;
	}

	~TypedHeapSlice () {
		delete[] this->_begin;
	}
};

typedef TypedHeapSlice<uint8_t> HeapSlice;

template <size_t N>
using StackSlice = TypedStackSlice<uint8_t, N>;

typedef TypedSlice<uint8_t> Slice;
<commit_msg>slice: account for sizeof(T) when writing destructively<commit_after>#pragma once

#include <algorithm>
#include <cassert>

namespace {
	template <typename T>
	void swapEndian (T* p) {
		uint8_t* q = reinterpret_cast<uint8_t*>(p);

		std::reverse(q, q + sizeof(T));
	}
}

template <typename T>
struct TypedFixedSlice {
protected:
	T* _begin;
	T* _end;

public:
	TypedFixedSlice () : _begin(nullptr), _end(nullptr) {}
	TypedFixedSlice (T* begin, T* end) : _begin(begin), _end(end) {
		assert(this->_begin);
		assert(this->_end);
	}

	auto begin () const { return this->_begin; }
	auto end () const { return this->_end; }

	auto drop (size_t n) const;
	auto take (size_t n) const;

	size_t length () const {
		return static_cast<size_t>(this->_end - this->_begin) / sizeof(T);
	}

	template <typename Y = T>
	auto peek (const size_t offset = 0) const {
		assert(offset + sizeof(Y) <= this->length());
		return *(reinterpret_cast<Y*>(this->_begin + offset));
	}

	template <typename Y, bool swap = false>
	void put (const Y value, size_t offset = 0) {
		assert(offset + sizeof(Y) <= this->length());
		auto ptr = reinterpret_cast<Y*>(this->_begin + offset);
		*ptr = value;

		if (swap) swapEndian(ptr);
	}

	auto& operator[] (const size_t i) {
		assert(i < this->length());
		return this->_begin[i];
	}

	const auto operator[] (const size_t i) const {
		assert(i < this->length());
		return this->_begin[i];
	}

	const auto operator< (const TypedFixedSlice<T>& rhs) const {
		return std::lexicographical_compare(this->_begin, this->_end, rhs._begin, rhs._end);
	}
};

template <typename T>
struct TypedSlice : public TypedFixedSlice<T> {
	TypedSlice () : TypedFixedSlice<T>() {}
	TypedSlice (T* begin, T* end) : TypedFixedSlice<T>(begin, end) {}

	void popFrontN (size_t n) {
		assert(n <= this->length());
		this->_begin += n;
	}

	void popFront () {
		this->popFrontN(1);
	}

	template <typename Y>
	auto read () {
		const auto value = this->template peek<Y>();
		this->popFrontN(sizeof(T) / sizeof(Y));
		return value;
	}

	template <typename Y, bool swap = false>
	void write (const Y value) {
		this->template put<Y, swap>(value);
		this->popFrontN(sizeof(Y) / sizeof(T));
	}

	template <typename Y>
	void writeN (const Y* data, size_t n) {
		assert(n <= this->length());
		memcpy(this->_begin, data, n);
		this->popFrontN(n * sizeof(T));
	}
};

template <typename T>
auto TypedFixedSlice<T>::drop (const size_t n) const {
	assert(n <= this->length());
	return TypedSlice<T>(this->_begin + n, this->_end);
}

template <typename T>
auto TypedFixedSlice<T>::take (const size_t n) const {
	assert(n <= this->length());
	return TypedSlice<T>(this->_begin, this->_begin + n);
}

template <typename T, size_t N>
struct TypedStackSlice : TypedFixedSlice<T> {
private:
	T data[N];

public:
	TypedStackSlice () : TypedFixedSlice<T>(data, data + N) {}
// 	TypedStackSlice (const TypedStackSlice& copy) {
// 		memcpy(this->_begin, copy._begin, N);
// 	}
};

template <typename T>
struct TypedHeapSlice : TypedFixedSlice<T> {
	TypedHeapSlice (const size_t n) : TypedFixedSlice<T>() {
		this->_begin = new T[n];
		this->_end = this->_begin + n;
	}

	~TypedHeapSlice () {
		delete[] this->_begin;
	}
};

typedef TypedHeapSlice<uint8_t> HeapSlice;

template <size_t N>
using StackSlice = TypedStackSlice<uint8_t, N>;

typedef TypedSlice<uint8_t> Slice;
<|endoftext|>


<commit_before>#include <string.h>
#include <stdlib.h>

#include "allfiles.h"
#include "debug.h"
#include "graphics.h"
#include "newfatal.h"
#include "sprites.h"
#include "sprbanks.h"
#include "people.h"
#include "sludger.h"
#include "objtypes.h"
#include "region.h"
#include "backdrop.h"
#include "talk.h"
#include "fonttext.h"
#include "statusba.h"
#include "freeze.h"
#include "zbuffer.h"

extern onScreenPerson * allPeople;
extern screenRegion * allScreenRegions;
extern screenRegion * overRegion;
extern speechStruct * speech;
extern inputType input;
extern GLuint backdropTextureName;
extern parallaxLayer * parallaxStuff;
extern int lightMapNumber, zBufferNumber;
extern eventHandlers * currentEvents;
extern personaAnimation * mouseCursorAnim;
extern int mouseCursorFrameNum;
extern int cameraX, cameraY;
extern unsigned int sceneWidth, sceneHeight;
extern float cameraZoom;
extern zBufferData zBuffer;
extern bool backdropExists;

frozenStuffStruct * frozenStuff = NULL;

extern unsigned int sceneWidth, sceneHeight;

void shufflePeople ();

GLuint freezeTextureName = 0;

void freezeGraphics() {
	glViewport (0, 0, realWinWidth, realWinHeight);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, (GLdouble) winWidth / cameraZoom, 0, (GLdouble) winHeight / cameraZoom, 1.0, -1.0);
	glMatrixMode(GL_MODELVIEW);

	glGenTextures (1, &freezeTextureName);
	int w = winWidth;
	int h = winHeight;
	if (! NPOT_textures) {
		w = getNextPOT(winWidth);
		h = getNextPOT(winHeight);
	}

	glBindTexture(GL_TEXTURE_2D, freezeTextureName);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);

	// Render scene
	glDepthMask (GL_TRUE);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	// Clear The Screen
	glDepthMask (GL_FALSE);

	// Temporarily disable AA
	int antiAlias = gameSettings.antiAlias;
	gameSettings.antiAlias = 0;

	drawBackDrop ();				// Draw the room
	drawZBuffer(cameraX, cameraY, false);

	glEnable(GL_DEPTH_TEST);
	drawPeople ();					// Then add any moving characters...
	glDisable(GL_DEPTH_TEST);

	gameSettings.antiAlias = antiAlias;

	// Copy Our ViewPort To The Texture
	glBindTexture(GL_TEXTURE_2D, freezeTextureName);
	glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, winWidth, winHeight);

	glViewport (viewportOffsetX, viewportOffsetY, viewportWidth, viewportHeight);
	setPixelCoords(false);
}

bool freeze () {
	debugOut("calling freeze()\n");
	frozenStuffStruct * newFreezer = new frozenStuffStruct;
	if (! checkNew (newFreezer)) return false;

	// Grab a copy of the current scene
	freezeGraphics();

	newFreezer -> backdropTextureName = backdropTextureName;

	int picWidth = sceneWidth;
	int picHeight = sceneHeight;
	if (! NPOT_textures) {
		picWidth = getNextPOT(picWidth);
		picHeight = getNextPOT(picHeight);
	}
	newFreezer -> backdropTexture = new GLubyte [picHeight*picWidth*4];
	saveTexture(backdropTextureName, newFreezer->backdropTexture);

	backdropTextureName = 0;

	newFreezer -> sceneWidth = sceneWidth;
	newFreezer -> sceneHeight = sceneHeight;
	newFreezer -> cameraX = cameraX;
	newFreezer -> cameraY = cameraY;
	newFreezer -> cameraZoom = cameraZoom;

	newFreezer -> lightMapTexture = lightMap.data;
	newFreezer -> lightMapTextureName = lightMap.name;
	newFreezer -> lightMapNumber = lightMapNumber;
	lightMap.data = NULL;
	lightMap.name = 0;

	newFreezer -> parallaxStuff = parallaxStuff;
	parallaxStuff = NULL;

	newFreezer -> zBufferImage = zBuffer.tex;
	newFreezer -> zBufferNumber = zBuffer.originalNum;
	newFreezer -> zPanels = zBuffer.numPanels;
	zBuffer.tex = NULL;

	// resizeBackdrop kills parallax stuff, light map, z-buffer...
	if (! resizeBackdrop (winWidth, winHeight)) return fatal ("Can't create new temporary backdrop buffer");

	if (! NPOT_textures) {
		picWidth = getNextPOT(sceneWidth);
		picHeight = getNextPOT(sceneHeight);
		backdropTexW = (double) sceneWidth / picWidth;
		backdropTexH = (double) sceneHeight / picHeight;
	}

	// Copy the old scene to the new backdrop
	glDeleteTextures (1, &backdropTextureName);
	backdropTextureName = freezeTextureName;
	backdropExists = true;

	// Free texture memory used by old stuff
	parallaxStuff = newFreezer -> parallaxStuff;
	while (parallaxStuff) {
		glDeleteTextures (1, &parallaxStuff -> textureName);
		parallaxStuff = parallaxStuff -> next;
	}
	if (newFreezer -> zBufferImage) {
		glDeleteTextures (1, &zBuffer.texName);
	}
	if (newFreezer -> lightMapTextureName) {
		glDeleteTextures (1, &newFreezer -> lightMapTextureName);
	}
	if (newFreezer -> backdropTextureName) {
		glDeleteTextures (1, &newFreezer -> backdropTextureName);
	}

	newFreezer -> allPeople = allPeople;
	allPeople = NULL;

	statusStuff * newStatusStuff = new statusStuff;
	if (! checkNew (newStatusStuff)) return false;
	newFreezer -> frozenStatus = copyStatusBarStuff (newStatusStuff);

	newFreezer -> allScreenRegions = allScreenRegions;
	allScreenRegions = NULL;
	overRegion = NULL;

	newFreezer -> mouseCursorAnim = mouseCursorAnim;
	newFreezer -> mouseCursorFrameNum = mouseCursorFrameNum;
	mouseCursorAnim = makeNullAnim ();
	mouseCursorFrameNum = 0;

	newFreezer -> speech = speech;
	initSpeech ();

	newFreezer -> currentEvents = currentEvents;
	currentEvents = new eventHandlers;
	if (! checkNew (currentEvents)) return false;
	memset (currentEvents, 0, sizeof (eventHandlers));

	newFreezer -> next = frozenStuff;
	frozenStuff = newFreezer;
	return true;
}

int howFrozen () {
	int a = 0;
	frozenStuffStruct * f = frozenStuff;
	while (f) {
		a ++;
		f = f -> next;
	}
	return a;
}

extern GLubyte * backdropTexture;

void unfreeze (bool killImage) {
	frozenStuffStruct * killMe = frozenStuff;

	if (! frozenStuff) return;

	sceneWidth = frozenStuff -> sceneWidth;
	sceneHeight = frozenStuff -> sceneHeight;

	cameraX = frozenStuff -> cameraX;
	cameraY = frozenStuff -> cameraY;
	input.mouseX = (int)(input.mouseX * cameraZoom);
	input.mouseY = (int)(input.mouseY * cameraZoom);
	cameraZoom = frozenStuff -> cameraZoom;
	input.mouseX = (int)(input.mouseX / cameraZoom);
	input.mouseY = (int)(input.mouseY / cameraZoom);
	setPixelCoords(false);

	killAllPeople ();
	allPeople = frozenStuff -> allPeople;

	killAllRegions ();
	allScreenRegions = frozenStuff -> allScreenRegions;

	killLightMap ();
	lightMap.data = frozenStuff -> lightMapTexture;
	lightMap.name = frozenStuff -> lightMapTextureName;
	lightMapNumber = frozenStuff -> lightMapNumber;
	if (lightMapNumber) {
		lightMap.name = 0;
		loadLightMap(lightMapNumber);
	}

	killZBuffer ();
	zBuffer.tex = frozenStuff -> zBufferImage;
	zBuffer.originalNum = frozenStuff -> zBufferNumber;
	zBuffer.numPanels = frozenStuff -> zPanels;
	if (zBuffer.numPanels) {
		zBuffer.texName = 0;
		setZBuffer (zBuffer.originalNum);
	}

	killParallax ();
	parallaxStuff = frozenStuff -> parallaxStuff;
	reloadParallaxTextures ();

	if (killImage) killBackDrop ();
	backdropTextureName = frozenStuff -> backdropTextureName;
	if (backdropTexture) delete backdropTexture;
	backdropTexture = frozenStuff -> backdropTexture;
	backdropExists = true;
	if (backdropTextureName) {
		backdropTextureName = 0;
		glGenTextures (1, &backdropTextureName);
		glBindTexture (GL_TEXTURE_2D, backdropTextureName);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

		if (gameSettings.antiAlias < 0) {
			glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
			glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		} else {
			glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
			glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		}

		int picWidth = sceneWidth;
		int picHeight = sceneHeight;
		if (! NPOT_textures) {
			picWidth = getNextPOT(picWidth);
			picHeight = getNextPOT(picHeight);
		}
		// Restore the backdrop
		glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, frozenStuff -> backdropTexture);

	}

	deleteAnim (mouseCursorAnim);
	mouseCursorAnim = frozenStuff -> mouseCursorAnim;
	mouseCursorFrameNum = frozenStuff -> mouseCursorFrameNum;

	restoreBarStuff (frozenStuff -> frozenStatus);

	delete currentEvents;
	currentEvents = frozenStuff -> currentEvents;

	killAllSpeech ();
	delete speech;
	speech = frozenStuff -> speech;

	frozenStuff = frozenStuff -> next;

	overRegion = NULL;
	delete killMe;
	killMe = NULL;
}
<commit_msg>Engine: Once again, I had messed up the freezing code without noticing. (Aargh!) I noticed it now when I finally had time to work on my own game, so now it's fixed and works again (except in the case where the game window is larger than the screen - that still needs to be fixed).<commit_after>#include <string.h>
#include <stdlib.h>

#include "allfiles.h"
#include "debug.h"
#include "graphics.h"
#include "newfatal.h"
#include "sprites.h"
#include "sprbanks.h"
#include "people.h"
#include "sludger.h"
#include "objtypes.h"
#include "region.h"
#include "backdrop.h"
#include "talk.h"
#include "fonttext.h"
#include "statusba.h"
#include "freeze.h"
#include "zbuffer.h"

extern onScreenPerson * allPeople;
extern screenRegion * allScreenRegions;
extern screenRegion * overRegion;
extern speechStruct * speech;
extern inputType input;
extern GLuint backdropTextureName;
extern parallaxLayer * parallaxStuff;
extern int lightMapNumber, zBufferNumber;
extern eventHandlers * currentEvents;
extern personaAnimation * mouseCursorAnim;
extern int mouseCursorFrameNum;
extern int cameraX, cameraY;
extern unsigned int sceneWidth, sceneHeight;
extern float cameraZoom;
extern zBufferData zBuffer;
extern bool backdropExists;

frozenStuffStruct * frozenStuff = NULL;

extern unsigned int sceneWidth, sceneHeight;

void shufflePeople ();

GLuint freezeTextureName = 0;

void freezeGraphics() {
	// Warning: This doesn't work if winWidth > realWinWidth || winHeight > realWinHeight!
	// TODO: A workaround for that (very unusual) special case is needed.
	glViewport (0, 0, winWidth, winHeight);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, (GLdouble) winWidth / cameraZoom, 0, (GLdouble) winHeight / cameraZoom, 1.0, -1.0);
	glMatrixMode(GL_MODELVIEW);

	glGenTextures (1, &freezeTextureName);
	int w = winWidth;
	int h = winHeight;
	if (! NPOT_textures) {
		w = getNextPOT(winWidth);
		h = getNextPOT(winHeight);
	}

	glBindTexture(GL_TEXTURE_2D, freezeTextureName);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);

	// Render scene
	glDepthMask (GL_TRUE);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	// Clear The Screen
	glDepthMask (GL_FALSE);

	// Temporarily disable AA
	int antiAlias = gameSettings.antiAlias;
	gameSettings.antiAlias = 0;

	drawBackDrop ();				// Draw the room
	drawZBuffer(cameraX, cameraY, false);

	glEnable(GL_DEPTH_TEST);
	drawPeople ();					// Then add any moving characters...
	glDisable(GL_DEPTH_TEST);

	gameSettings.antiAlias = antiAlias;

	// Copy Our ViewPort To The Texture
	glBindTexture(GL_TEXTURE_2D, freezeTextureName);
	glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, winWidth, winHeight);

	glViewport (viewportOffsetX, viewportOffsetY, viewportWidth, viewportHeight);
	setPixelCoords(false);
}

bool freeze () {
	debugOut("calling freeze()\n");
	frozenStuffStruct * newFreezer = new frozenStuffStruct;
	if (! checkNew (newFreezer)) return false;

	// Grab a copy of the current scene
	freezeGraphics();

	newFreezer -> backdropTextureName = backdropTextureName;

	int picWidth = sceneWidth;
	int picHeight = sceneHeight;
	if (! NPOT_textures) {
		picWidth = getNextPOT(picWidth);
		picHeight = getNextPOT(picHeight);
	}
	newFreezer -> backdropTexture = new GLubyte [picHeight*picWidth*4];
	saveTexture(backdropTextureName, newFreezer->backdropTexture);

	backdropTextureName = 0;

	newFreezer -> sceneWidth = sceneWidth;
	newFreezer -> sceneHeight = sceneHeight;
	newFreezer -> cameraX = cameraX;
	newFreezer -> cameraY = cameraY;
	newFreezer -> cameraZoom = cameraZoom;

	newFreezer -> lightMapTexture = lightMap.data;
	newFreezer -> lightMapTextureName = lightMap.name;
	newFreezer -> lightMapNumber = lightMapNumber;
	lightMap.data = NULL;
	lightMap.name = 0;

	newFreezer -> parallaxStuff = parallaxStuff;
	parallaxStuff = NULL;

	newFreezer -> zBufferImage = zBuffer.tex;
	newFreezer -> zBufferNumber = zBuffer.originalNum;
	newFreezer -> zPanels = zBuffer.numPanels;
	zBuffer.tex = NULL;

	// resizeBackdrop kills parallax stuff, light map, z-buffer...
	if (! resizeBackdrop (winWidth, winHeight)) return fatal ("Can't create new temporary backdrop buffer");

	if (! NPOT_textures) {
		picWidth = getNextPOT(sceneWidth);
		picHeight = getNextPOT(sceneHeight);
		backdropTexW = (double) sceneWidth / picWidth;
		backdropTexH = (double) sceneHeight / picHeight;
	}

	// Copy the old scene to the new backdrop
	glDeleteTextures (1, &backdropTextureName);
	backdropTextureName = freezeTextureName;
	backdropExists = true;

	// Free texture memory used by old stuff
	parallaxStuff = newFreezer -> parallaxStuff;
	while (parallaxStuff) {
		glDeleteTextures (1, &parallaxStuff -> textureName);
		parallaxStuff = parallaxStuff -> next;
	}
	if (newFreezer -> zBufferImage) {
		glDeleteTextures (1, &zBuffer.texName);
	}
	if (newFreezer -> lightMapTextureName) {
		glDeleteTextures (1, &newFreezer -> lightMapTextureName);
	}
	if (newFreezer -> backdropTextureName) {
		glDeleteTextures (1, &newFreezer -> backdropTextureName);
	}

	newFreezer -> allPeople = allPeople;
	allPeople = NULL;

	statusStuff * newStatusStuff = new statusStuff;
	if (! checkNew (newStatusStuff)) return false;
	newFreezer -> frozenStatus = copyStatusBarStuff (newStatusStuff);

	newFreezer -> allScreenRegions = allScreenRegions;
	allScreenRegions = NULL;
	overRegion = NULL;

	newFreezer -> mouseCursorAnim = mouseCursorAnim;
	newFreezer -> mouseCursorFrameNum = mouseCursorFrameNum;
	mouseCursorAnim = makeNullAnim ();
	mouseCursorFrameNum = 0;

	newFreezer -> speech = speech;
	initSpeech ();

	newFreezer -> currentEvents = currentEvents;
	currentEvents = new eventHandlers;
	if (! checkNew (currentEvents)) return false;
	memset (currentEvents, 0, sizeof (eventHandlers));

	newFreezer -> next = frozenStuff;
	frozenStuff = newFreezer;
	return true;
}

int howFrozen () {
	int a = 0;
	frozenStuffStruct * f = frozenStuff;
	while (f) {
		a ++;
		f = f -> next;
	}
	return a;
}

extern GLubyte * backdropTexture;

void unfreeze (bool killImage) {
	frozenStuffStruct * killMe = frozenStuff;

	if (! frozenStuff) return;

	sceneWidth = frozenStuff -> sceneWidth;
	sceneHeight = frozenStuff -> sceneHeight;

	cameraX = frozenStuff -> cameraX;
	cameraY = frozenStuff -> cameraY;
	input.mouseX = (int)(input.mouseX * cameraZoom);
	input.mouseY = (int)(input.mouseY * cameraZoom);
	cameraZoom = frozenStuff -> cameraZoom;
	input.mouseX = (int)(input.mouseX / cameraZoom);
	input.mouseY = (int)(input.mouseY / cameraZoom);
	setPixelCoords(false);

	killAllPeople ();
	allPeople = frozenStuff -> allPeople;

	killAllRegions ();
	allScreenRegions = frozenStuff -> allScreenRegions;

	killLightMap ();
	lightMap.data = frozenStuff -> lightMapTexture;
	lightMap.name = frozenStuff -> lightMapTextureName;
	lightMapNumber = frozenStuff -> lightMapNumber;
	if (lightMapNumber) {
		lightMap.name = 0;
		loadLightMap(lightMapNumber);
	}

	killZBuffer ();
	zBuffer.tex = frozenStuff -> zBufferImage;
	zBuffer.originalNum = frozenStuff -> zBufferNumber;
	zBuffer.numPanels = frozenStuff -> zPanels;
	if (zBuffer.numPanels) {
		zBuffer.texName = 0;
		setZBuffer (zBuffer.originalNum);
	}

	killParallax ();
	parallaxStuff = frozenStuff -> parallaxStuff;
	reloadParallaxTextures ();

	if (killImage) killBackDrop ();
	backdropTextureName = frozenStuff -> backdropTextureName;
	if (backdropTexture) delete backdropTexture;
	backdropTexture = frozenStuff -> backdropTexture;
	backdropExists = true;
	if (backdropTextureName) {
		backdropTextureName = 0;
		glGenTextures (1, &backdropTextureName);
		glBindTexture (GL_TEXTURE_2D, backdropTextureName);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

		if (gameSettings.antiAlias < 0) {
			glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
			glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		} else {
			glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
			glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		}

		int picWidth = sceneWidth;
		int picHeight = sceneHeight;
		if (! NPOT_textures) {
			picWidth = getNextPOT(picWidth);
			picHeight = getNextPOT(picHeight);
		}
		// Restore the backdrop
		glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, picWidth, picHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, frozenStuff -> backdropTexture);

	}

	deleteAnim (mouseCursorAnim);
	mouseCursorAnim = frozenStuff -> mouseCursorAnim;
	mouseCursorFrameNum = frozenStuff -> mouseCursorFrameNum;

	restoreBarStuff (frozenStuff -> frozenStatus);

	delete currentEvents;
	currentEvents = frozenStuff -> currentEvents;

	killAllSpeech ();
	delete speech;
	speech = frozenStuff -> speech;

	frozenStuff = frozenStuff -> next;

	overRegion = NULL;
	delete killMe;
	killMe = NULL;
}
<|endoftext|>