<commit_before>//
//  inpal_prime.cpp
//  Inverse Palindrome Library
//
//  Created by Bryan Triana
//  Copyright © 2016 Inverse Palindrome. All rights reserved.
//

#include "inpal_prime.hpp"
#include "inpal_algorithm.hpp"

std::vector<std::size_t> inpal::prime::prime_list(std::size_t range)
{
    const auto& primes = prime_sieve(range);
    std::vector<std::size_t> p_list;
    if(range < 2) return p_list;

    p_list.push_back(2);

    for(std::size_t i = 3; i <= range; i += 2) if(primes[i]) p_list.push_back(i);

    return p_list;
}

std::vector<bool> inpal::prime::prime_sieve(std::size_t range)
{
    std::vector<bool> p_test(range + 1, false);

    //sieve axioms
    for(std::size_t x = 1; x <= std::sqrt(range); x++)
        for(std::size_t y = 1; y <= std::sqrt(range); y++)
        {
            std::size_t i = (4 * x * x) + (y * y);
            if(i <= range && (i % 12 == 1 || i % 12 == 5)) p_test[i].flip();

            i = (3 * x * x) + (y * y);
            if(i <= range && i %12 == 7) p_test[i].flip();

            i = (3 * x * x) - (y * y);
            if(x > y && i <= range && i % 12 == 11) p_test[i].flip();
        }

    //marks 2, 3 and 5 as prime numbers
    p_test[2] = p_test[3] = p_test[5] = true;

    //marks all multiples of primes as non primes
    for(std::size_t r = 5; r <= std::sqrt(range); r++)
    {
        if(p_test[r])
        {
            for(std::size_t j = r * r; j <= range; j += r * r) p_test[j] = false;
        }
    }

    return p_test;
}

std::vector<std::size_t> inpal::prime::factor_list(std::size_t num)
{
    std::vector<std::size_t> factors;
    std::vector<std::size_t> primes;

    if(num < 2) return primes;

    std::size_t factor = algorithm::pollard_rho(num);
    factors.push_back(num / factor);
    factors.push_back(factor);

    do
    {
        std::size_t m = factors.back();
        factors.pop_back();

        if(m == 1) continue;
        if(prime_test(m))
        {
            primes.push_back(m);

            //decomposes the factors into primes
            for(std::size_t i = 0; i < factors.size(); i++)
            {
                std::size_t k = factors[i];
                if(k % m == 0)
                {
                    do k /= m;
                    while(k % m == 0);

                    factors[i] = k;
                }
            }
        }
        else
        {
            factor = algorithm::pollard_rho(m);
            factors.push_back(m / factor);
            factors.push_back(factor);
        }
    }
    while(factors.size());

    //prime factors found by pollard rho arent always ordered
    std::sort(primes.begin(), primes.end());

    return primes;
}

std::size_t inpal::prime::prime_locate(std::size_t pos)
{
    //index starts at 1 instead of 0, eg 1st prime is 2
    pos = pos - 1;

    //return values for input less or equal to 13
    const auto& small_primes = prime_list(43);
    if(pos < 14) return small_primes[pos];

    //denotes the limit of the sieve
    const std::size_t limit = ceil(pos * log(pos) + pos * log(log(pos)));
    const auto& primes = prime_list(limit);

    return primes[pos];
}

std::size_t inpal::prime::max_prime(std::size_t range)
{
    if(range < 2) throw std::invalid_argument("There are no prime numbers less than 2");

    for(std::size_t i = range; i > 0; i--) if(prime_test(i)) return i;

    return 2;
}

std::size_t inpal::prime::prime_count(std::size_t range)
{
    if(range < 2) return 0;
    if(range == 2) return 1;

    std::vector<bool> p_count(range / 2 + 1, true);

    //modified sieve of eratosthenes
    for(std::size_t i = 1; i <= std::sqrt(range / 2 + 1); i++)
    {
       if(p_count[i])
       {
           for(std::size_t j = 2 * i * (i + 1); j < range / 2 + 1; j += 2 * i + 1) p_count[j] = false;
       }
    }

    return std::count(p_count.begin(), p_count.end(), true);
}

double inpal::prime::prime_density(double range)
{
    return prime_count(range) / range;
}

bool inpal::prime::prime_test(std::size_t num)
{
    if(num < 2 || (num != 2 && num % 2 == 0)) return false;

    //iterations will occur 20 times to ensure that the margin of error is less than 4^-20
    const std::size_t cycle = 20;
    std::size_t s = num - 1;
    while(s % 2 == 0) s /= 2;

    for(std::size_t i = 0; i < cycle; i++)
    {
        std::size_t a = rand() % (num - 1) + 1;
        std::size_t b = s;
        std::size_t mod = algorithm::modulo(a, b, num);

        while(b != num - 1 && mod != 1 && mod != num - 1)
        {
            mod = algorithm::mulmod(mod, mod, num);
            b *= 2;
        }
        if(mod != num - 1 && b % 2 == 0) return false;
    }

    return true;
}

bool inpal::prime::twin_test(std::size_t num)
{
    return prime_test(num) && (prime_test(num - 2) || prime_test(num + 2));
}

bool inpal::prime::cousin_test(std::size_t num)
{
    return  prime_test(num) && (prime_test(num - 4) || prime_test(num + 4));
}

bool inpal::prime::sexy_test(std::size_t num)
{
    return num != 3 && prime_test(num) && (prime_test(num - 6) || prime_test(num + 6));
}

std::size_t inpal::prime::max_palprime(std::size_t range)
{
    if(range < 2) throw std::invalid_argument("There are no palindromic prime numbers less than 2");

    for(std::size_t i = range; i >= 2; --i) if(prime_test(i) && algorithm::pal_test(i)) return i;

    return 2;
}

std::size_t inpal::prime::max_factor(std::size_t num)
{
    if(num < 2) throw std::invalid_argument("There are no prime factors less than 2");

    return factor_list(num).back();
}

std::size_t inpal::prime::factor_count(std::size_t num)
{
    return factor_list(num).size();
}
<commit_msg>changed regular for-loop to range based for-loop<commit_after>//
//  inpal_prime.cpp
//  Inverse Palindrome Library
//
//  Created by Bryan Triana
//  Copyright © 2016 Inverse Palindrome. All rights reserved.
//

#include "inpal_prime.hpp"
#include "inpal_algorithm.hpp"

std::vector<std::size_t> inpal::prime::prime_list(std::size_t range)
{
    const auto& primes = prime_sieve(range);
    std::vector<std::size_t> p_list;
    if(range < 2) return p_list;

    p_list.push_back(2);

    for(std::size_t i = 3; i <= range; i += 2) if(primes[i]) p_list.push_back(i);

    return p_list;
}

std::vector<bool> inpal::prime::prime_sieve(std::size_t range)
{
    std::vector<bool> p_test(range + 1, false);

    //sieve axioms
    for(std::size_t x = 1; x <= std::sqrt(range); ++x)
        for(std::size_t y = 1; y <= std::sqrt(range); ++y)
        {
            std::size_t i = (4 * x * x) + (y * y);
            if(i <= range && (i % 12 == 1 || i % 12 == 5)) p_test[i].flip();

            i = (3 * x * x) + (y * y);
            if(i <= range && i %12 == 7) p_test[i].flip();

            i = (3 * x * x) - (y * y);
            if(x > y && i <= range && i % 12 == 11) p_test[i].flip();
        }

    //marks 2, 3 and 5 as prime numbers
    p_test[2] = p_test[3] = p_test[5] = true;

    //marks all multiples of primes as non primes
    for(std::size_t r = 5; r <= std::sqrt(range); ++r)
    {
        if(p_test[r])
        {
            for(std::size_t j = r * r; j <= range; j += r * r) p_test[j] = false;
        }
    }

    return p_test;
}

std::vector<std::size_t> inpal::prime::factor_list(std::size_t num)
{
    std::vector<std::size_t> factors;
    std::vector<std::size_t> primes;

    if(num < 2) return primes;

    std::size_t factor = algorithm::pollard_rho(num);
    factors.push_back(num / factor);
    factors.push_back(factor);

    do
    {
        std::size_t m = factors.back();
        factors.pop_back();

        if(m == 1) continue;
        if(prime_test(m))
        {
            primes.push_back(m);

            //decomposes the factors into primes
            for(auto& iterator : factors)
            {
                std::size_t k = iterator;
                if(k % m == 0)
                {
                    do k /= m;
                    while(k % m == 0);

                    iterator = k;
                }
            }
        }
        else
        {
            factor = algorithm::pollard_rho(m);
            factors.push_back(m / factor);
            factors.push_back(factor);
        }
    }
    while(factors.size());

    //prime factors found by pollard rho arent always ordered
    std::sort(primes.begin(), primes.end());

    return primes;
}

std::size_t inpal::prime::prime_locate(std::size_t pos)
{
    //index starts at 1 instead of 0, eg 1st prime is 2
    pos = pos - 1;

    //return values for input less or equal to 13
    const auto& small_primes = prime_list(43);
    if(pos < 14) return small_primes[pos];

    //limits the size of the sieve
    const std::size_t limit = ceil(pos * log(pos) + pos * log(log(pos)));
    const auto& primes = prime_list(limit);

    return primes[pos];
}

std::size_t inpal::prime::max_prime(std::size_t range)
{
    if(range < 2) throw std::invalid_argument("There are no prime numbers less than 2");

    for(std::size_t i = range; i > 0; --i) if(prime_test(i)) return i;

    return 2;
}

std::size_t inpal::prime::prime_count(std::size_t range)
{
    if(range < 2) return 0;
    if(range == 2) return 1;

    std::vector<bool> p_count(range / 2 + 1, true);

    //modified sieve of eratosthenes
    for(std::size_t i = 1; i <= std::sqrt(range / 2 + 1); ++i)
    {
        if(p_count[i])
        {
            for(std::size_t j = 2 * i * (i + 1); j < range / 2 + 1; j += 2 * i + 1) p_count[j] = false;
        }
    }

    return std::count(p_count.begin(), p_count.end(), true);
}

double inpal::prime::prime_density(double range)
{
    return prime_count(range) / range;
}

bool inpal::prime::prime_test(std::size_t num)
{
    if(num < 2 || (num != 2 && num % 2 == 0)) return false;

    //iterations will occur 20 times to ensure that the margin of error is less than 4^-20
    const std::size_t cycle = 20;
    std::size_t s = num - 1;
    while(s % 2 == 0) s /= 2;

    for(std::size_t i = 0; i < cycle; ++i)
    {
        std::size_t a = rand() % (num - 1) + 1;
        std::size_t b = s;
        std::size_t mod = algorithm::modulo(a, b, num);

        while(b != num - 1 && mod != 1 && mod != num - 1)
        {
            mod = algorithm::mulmod(mod, mod, num);
            b *= 2;
        }
        if(mod != num - 1 && b % 2 == 0) return false;
    }

    return true;
}

bool inpal::prime::twin_test(std::size_t num)
{
    return prime_test(num) && (prime_test(num - 2) || prime_test(num + 2));
}

bool inpal::prime::cousin_test(std::size_t num)
{
    return  prime_test(num) && (prime_test(num - 4) || prime_test(num + 4));
}

bool inpal::prime::sexy_test(std::size_t num)
{
    return num != 3 && prime_test(num) && (prime_test(num - 6) || prime_test(num + 6));
}

std::size_t inpal::prime::max_palprime(std::size_t range)
{
    if(range < 2) throw std::invalid_argument("There are no palindromic prime numbers less than 2");

    for(std::size_t i = range; i >= 2; --i) if(prime_test(i) && algorithm::pal_test(i)) return i;

    return 2;
}

std::size_t inpal::prime::max_factor(std::size_t num)
{
    if(num < 2) throw std::invalid_argument("There are no prime factors less than 2");

    return factor_list(num).back();
}

std::size_t inpal::prime::factor_count(std::size_t num)
{
    return factor_list(num).size();
}
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS jollyfilterteam03 (1.4.114); FILE MERGED 2003/03/13 12:02:49 cmc 1.4.114.1: #i3371# when we export a pagebreak, have a check to see if it would use a different page descriptor because of followstyles etc and if so export a sectionbreak, will help paper over the lack of pagestyles in word export.<commit_after><|endoftext|>


<commit_before>#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <getopt.h>
#include <TROOT.h>
#include <TTree.h>
#include <TFile.h>

//#define ADC_PACKET 0xadc1
#define ADC_PACKET 104
#define BUFFERSIZE 4096
#define BUFFER_TYPE_DATA 1
#define BUFFER_TYPE_END 12

#define CAEN_GEO_MASK 0xf8000000
#define CAEN_TYPE_MASK 0x07000000
#define CAEN_HEADER_CRATE_MASK 0x00ff0000
#define CAEN_HEADER_CNT_MASK 0x00003f00
#define CAEN_DATA_CHAN_MASK 0x001f0000
#define CAEN_DATA_UN_MASK 0x00002000
#define CAEN_DATA_OV_MASK 0x00001000
#define CAEN_DATA_VAL_MASK 0x00000fff
#define CAEN_EOB_COUNT_MASK 0x00ffffff
#define CAEN_HEADER 0x02000000
#define CAEN_DATA 0x00000000
#define CAEN_EOB 0x04000000

class adc
{
public:
	Int_t ch[32];
	adc() {Reset();};
	void Reset(){for (int i=0; i<32; ++i){ch[i]=0;}};
};

int getArgs(int argc,char **argv);

typedef struct
{
	char filein[100];
	char fileout[100];
} gParameters;

/*
 * Options specified on the command line
 * -i <filename> -- file containing list of input files
 * -o <filename> -- output root file
 */
gParameters gParams={"inputs.dat", "out.root"};

int main (int argc, char *argv[])
{
	FILE *flist; // File containing list of input filenames
	FILE *fp; // Input files
	char line[256];
	int nEvents = 0;

	/* Make sure the args are good. This should never happen */
	if (getArgs(argc,argv)!=0) {
		fprintf(stderr,"ERROR: Invalid input!\n");
		exit(-1);
	}

	/* Make sure flist is good */
	if ((flist=fopen(gParams.filein,"r"))==NULL)
	{
		fprintf(stderr,"ERROR: Can't open input file %s !\n",gParams.filein);
		exit(-2);
	}

	adc* adc01 = new adc();
	TFile *outfile = new TFile(gParams.fileout,"RECREATE");
	TTree *tree = new TTree("tree","Events");
	tree->Branch("adc01",adc01,"adc01[32]/I");

	/* Loop over input files */
	while (fgets(line,256,flist))
	{
		printf("Reading %s", line);
		int strLen = strlen(line);

		if ((int)(line[strLen-1]) == '\n')
		{
			line[strLen-1] = '\0';
		}

		if ((fp=fopen(line,"r"))==NULL)
		{
			fprintf(stderr,"Can't open evtfile %s, moving to next file\n",line);
			continue;
		}

		/* Read in buffers. Buffer structure: http://www.nscl.msu.edu/exp/performingexp/resources/daq#chapter4 */
		unsigned short int buffer[BUFFERSIZE];
		while (fread(buffer, 2, BUFFERSIZE, fp) == BUFFERSIZE && !feof(fp))
		{
			int index = 0;
			/* Buffer Header */
			unsigned short int bufferSize = buffer[index++];
			unsigned short int bufferType = buffer[index++];
			unsigned short int bufferChecksum = buffer[index++];
			unsigned short int runNum = buffer[index++];
			unsigned short int bufferSeq[2] = {buffer[index++],buffer[index++]};
			unsigned short int numEvents = buffer[index++];
			unsigned short int numLAM = buffer[index++];
			unsigned short int numCPUs = buffer[index++];
			unsigned short int numBitReg = buffer[index++];
			unsigned short int bufferRev = buffer[index++];
			index += 5; // Rest of header, unused

			//printf("Begin Buffer: %d\n", bufferType);

			/* Events -- Only if this is a data buffer */
			if (bufferType == BUFFER_TYPE_DATA)
			{
				for (int currEvent = 0; currEvent < numEvents; ++currEvent)
				{
					int eventRead = 1;
					unsigned short int eventSize = buffer[index++];

					//printf("Begin Event: %d, %d\n", currEvent, eventSize);
					++nEvents;
					while (eventRead < eventSize)
					{
						unsigned short int packetSize = buffer[index++];
						unsigned short int packetID = buffer[index++];
						int packetRead = 2;
						//printf("Start Packet: %d, %d\n", packetSize, packetID);

						/* Sanity Checks */
						if (packetSize > BUFFERSIZE)
						{
							fprintf(stderr, "packetSize (%d) > BUFFERSIZE (%d)\n", packetSize, BUFFERSIZE);
							exit(2);
						}
						if (packetSize > eventSize-eventRead)
						{
							printf("packetSize (%d) > eventSize-eventRead (%d). Skipping to next event.\n", packetSize, eventSize-eventRead);
							eventRead += eventSize-eventRead;
							continue;
						}

						/* Here we can have different packets. This is the stuff you want to change. */
						switch(packetID)
						{
						case ADC_PACKET:
							while (packetRead < packetSize)
							{
								unsigned int data;
								unsigned int geo;
								unsigned int type;
								unsigned int crate;
								unsigned int cnt;
								unsigned int chan;
								unsigned int val;
								unsigned int count;
								bool un;
								bool ov;

								/* Each 32-bit word is actually stored as 2 16-bit words reversed for some reason */
								data = buffer[index++]*0x10000;
								data += buffer[index++];
								packetRead += 2;

								/* Caen V785 buffer structure: http://www.caen.it/csite/CaenProd.jsp?parent=11&idmod=37 */
								geo = (data & CAEN_GEO_MASK)>>27;
								type = data & CAEN_TYPE_MASK;
								switch(type)
								{
								case CAEN_HEADER:
									crate = (data& CAEN_HEADER_CRATE_MASK)>>16;
									cnt = (data& CAEN_HEADER_CNT_MASK)>>8;
									//printf ("HEADER: GEO: %x CRATE: %x CNT: %x\n", geo, crate, cnt);
									break;
								case CAEN_DATA:
									chan = (data & CAEN_DATA_CHAN_MASK)>>16;
									un = data & CAEN_DATA_UN_MASK;
									ov = data & CAEN_DATA_OV_MASK;
									val = data & CAEN_DATA_VAL_MASK;
									adc01->ch[chan] = val;
									//printf ("DATA: GEO: %x CHAN: %x UN: %x OV: %x VAL: %x\n", geo, chan, un, ov, val);
									break;
								case CAEN_EOB:
									count = data & CAEN_EOB_COUNT_MASK;
									//printf ("EOB: GEO: %x COUNT: %x\n", geo, count);
									break;
								}
							}
							break;
						default:
							index += packetSize-2;
							printf("WARNING: Unknown packetID: %x\n", packetID);
							break;
						}

						/* Sanity Check */
						if (packetRead != packetSize)
						{
							fprintf(stderr, "For packetID %x: packetRead (%d) != packetSize (%d)\n", packetID, packetRead, packetSize);
							exit(2);
						}

						eventRead += packetSize;
					}

					if (eventRead != eventSize)
					{
						fprintf(stderr, "eventRead (%d) != eventSize (%d)\n", eventRead, eventSize);
						exit(2);
					}
					tree->Fill();
					adc01->Reset();
				}
			}
/*
			// I think this is unneeded
			else if (bufferType == BUFFER_TYPE_END)
			{
				break;
			}
*/
		}
		fclose(fp);
		printf(" Done\n");
	}

	fclose(flist);

	/* Write and close output file */
	tree->Print();
	outfile->Write();
	outfile->Close();

	return 0;
}

int getArgs(int argc, char**argv)
{
	char opt;
	int good = 0;

	while ((opt = (char)getopt(argc, argv, "i:o:")) != EOF)
	{
		switch (opt)
		{
			case 'i': strcpy(gParams.filein,optarg); break;
			case 'o': strcpy(gParams.fileout,optarg); break;
		}
	}

	return (good);
}
<commit_msg>Consistent style<commit_after>/*
 *
 */
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <getopt.h>
#include <TROOT.h>
#include <TTree.h>
#include <TFile.h>

//#define ADC_PACKET 0xadc1
#define ADC_PACKET 104
#define BUFFERSIZE 4096
#define BUFFER_TYPE_DATA 1
#define BUFFER_TYPE_END 12

#define CAEN_GEO_MASK 0xf8000000
#define CAEN_TYPE_MASK 0x07000000
#define CAEN_HEADER_CRATE_MASK 0x00ff0000
#define CAEN_HEADER_CNT_MASK 0x00003f00
#define CAEN_DATA_CHAN_MASK 0x001f0000
#define CAEN_DATA_UN_MASK 0x00002000
#define CAEN_DATA_OV_MASK 0x00001000
#define CAEN_DATA_VAL_MASK 0x00000fff
#define CAEN_EOB_COUNT_MASK 0x00ffffff
#define CAEN_HEADER 0x02000000
#define CAEN_DATA 0x00000000
#define CAEN_EOB 0x04000000

class adc
{
public:
	Int_t ch[32];
	adc() {Reset();};
	void Reset(){for (int i=0; i<32; ++i){ch[i]=0;}};
};

int getArgs(int argc,char **argv);

typedef struct
{
	char filein[100];
	char fileout[100];
} gParameters;

/*
 * Options specified on the command line
 * -i <filename> -- file containing list of input files
 * -o <filename> -- output root file
 */
gParameters gParams={"inputs.dat", "out.root"};

int main (int argc, char *argv[])
{
	FILE *flist; // File containing list of input filenames
	FILE *fp; // Input files
	char line[256];
	int nEvents = 0;

	/* Make sure the args are good. This should never happen */
	if (getArgs(argc,argv)!=0)
	{
		fprintf(stderr,"ERROR: Invalid input!\n");
		exit(-1);
	}

	/* Make sure flist is good */
	if ((flist=fopen(gParams.filein,"r"))==NULL)
	{
		fprintf(stderr,"ERROR: Can't open input file %s !\n",gParams.filein);
		exit(-2);
	}

	adc* adc01 = new adc();
	TFile *outfile = new TFile(gParams.fileout,"RECREATE");
	TTree *tree = new TTree("tree","Events");
	tree->Branch("adc01",adc01,"adc01[32]/I");

	/* Loop over input files */
	while (fgets(line,256,flist))
	{
		printf("Reading %s", line);
		int strLen = strlen(line);

		if ((int)(line[strLen-1]) == '\n')
		{
			line[strLen-1] = '\0';
		}

		if ((fp=fopen(line,"r"))==NULL)
		{
			fprintf(stderr,"Can't open evtfile %s, moving to next file\n",line);
			continue;
		}

		/* Read in buffers. Buffer structure: http://www.nscl.msu.edu/exp/performingexp/resources/daq#chapter4 */
		unsigned short int buffer[BUFFERSIZE];
		while (fread(buffer, 2, BUFFERSIZE, fp) == BUFFERSIZE && !feof(fp))
		{
			int index = 0;
			/* Buffer Header */
			unsigned short int bufferSize = buffer[index++];
			unsigned short int bufferType = buffer[index++];
			unsigned short int bufferChecksum = buffer[index++];
			unsigned short int runNum = buffer[index++];
			unsigned short int bufferSeq[2] = {buffer[index++],buffer[index++]};
			unsigned short int numEvents = buffer[index++];
			unsigned short int numLAM = buffer[index++];
			unsigned short int numCPUs = buffer[index++];
			unsigned short int numBitReg = buffer[index++];
			unsigned short int bufferRev = buffer[index++];
			index += 5; // Rest of header, unused

			//printf("Begin Buffer: %d\n", bufferType);

			/* Events -- Only if this is a data buffer */
			if (bufferType == BUFFER_TYPE_DATA)
			{
				for (int currEvent = 0; currEvent < numEvents; ++currEvent)
				{
					int eventRead = 1;
					unsigned short int eventSize = buffer[index++];

					//printf("Begin Event: %d, %d\n", currEvent, eventSize);
					++nEvents;
					while (eventRead < eventSize)
					{
						unsigned short int packetSize = buffer[index++];
						unsigned short int packetID = buffer[index++];
						int packetRead = 2;
						//printf("Start Packet: %d, %d\n", packetSize, packetID);

						/* Sanity Checks */
						if (packetSize > BUFFERSIZE)
						{
							fprintf(stderr, "packetSize (%d) > BUFFERSIZE (%d)\n", packetSize, BUFFERSIZE);
							exit(2);
						}
						if (packetSize > eventSize-eventRead)
						{
							printf("packetSize (%d) > eventSize-eventRead (%d). Skipping to next event.\n", packetSize, eventSize-eventRead);
							eventRead += eventSize-eventRead;
							continue;
						}

						/* Here we can have different packets. This is the stuff you want to change. */
						switch(packetID)
						{
						case ADC_PACKET:
							while (packetRead < packetSize)
							{
								unsigned int data;
								unsigned int geo;
								unsigned int type;
								unsigned int crate;
								unsigned int cnt;
								unsigned int chan;
								unsigned int val;
								unsigned int count;
								bool un;
								bool ov;

								/* Each 32-bit word is actually stored as 2 16-bit words reversed for some reason */
								data = buffer[index++]*0x10000;
								data += buffer[index++];
								packetRead += 2;

								/* Caen V785 buffer structure: http://www.caen.it/csite/CaenProd.jsp?parent=11&idmod=37 */
								geo = (data & CAEN_GEO_MASK)>>27;
								type = data & CAEN_TYPE_MASK;
								switch(type)
								{
								case CAEN_HEADER:
									crate = (data& CAEN_HEADER_CRATE_MASK)>>16;
									cnt = (data& CAEN_HEADER_CNT_MASK)>>8;
									//printf ("HEADER: GEO: %x CRATE: %x CNT: %x\n", geo, crate, cnt);
									break;
								case CAEN_DATA:
									chan = (data & CAEN_DATA_CHAN_MASK)>>16;
									un = data & CAEN_DATA_UN_MASK;
									ov = data & CAEN_DATA_OV_MASK;
									val = data & CAEN_DATA_VAL_MASK;
									adc01->ch[chan] = val;
									//printf ("DATA: GEO: %x CHAN: %x UN: %x OV: %x VAL: %x\n", geo, chan, un, ov, val);
									break;
								case CAEN_EOB:
									count = data & CAEN_EOB_COUNT_MASK;
									//printf ("EOB: GEO: %x COUNT: %x\n", geo, count);
									break;
								}
							}
							break;
						default:
							index += packetSize-2;
							printf("WARNING: Unknown packetID: %x\n", packetID);
							break;
						}

						/* Sanity Check */
						if (packetRead != packetSize)
						{
							fprintf(stderr, "For packetID %x: packetRead (%d) != packetSize (%d)\n", packetID, packetRead, packetSize);
							exit(2);
						}

						eventRead += packetSize;
					}

					if (eventRead != eventSize)
					{
						fprintf(stderr, "eventRead (%d) != eventSize (%d)\n", eventRead, eventSize);
						exit(2);
					}
					tree->Fill();
					adc01->Reset();
				}
			}
/*
			// I think this is unneeded
			else if (bufferType == BUFFER_TYPE_END)
			{
				break;
			}
*/
		}
		fclose(fp);
		printf(" Done\n");
	}

	fclose(flist);

	/* Write and close output file */
	tree->Print();
	outfile->Write();
	outfile->Close();

	return 0;
}

int getArgs(int argc, char**argv)
{
	char opt;
	int good = 0;

	while ((opt = (char)getopt(argc, argv, "i:o:")) != EOF)
	{
		switch (opt)
		{
			case 'i': strcpy(gParams.filein,optarg); break;
			case 'o': strcpy(gParams.fileout,optarg); break;
		}
	}

	return (good);
}
<|endoftext|>


<commit_before>#include "exporter.h"
#include "videofile.h"

#include <QtDebug>

class AssertFailed {
public:
    AssertFailed(const QString& cond, const QString& file, int line,
                 QString extra = QString())
    {
        m_message = QString("%1:%2: assertion '%3' failed")
                .arg(file).arg(line).arg(cond);

        if (extra.size())
            m_message += ". " + extra + ".";
    }
    QString message() const { return m_message; }
    const char * cMessage() const { return m_message.toLocal8Bit().constData(); }
protected:
    QString m_message;
};

#define TRY_ASSERT(cond) \
    do { if (!cond) { throw AssertFailed(#cond, __FILE__, __LINE__); } } while (0)
#define TRY_ASSERT_X(cond, message) \
    do { if (!cond) { throw AssertFailed(#cond, __FILE__, __LINE__, message); \
    } } while (0)

Exporter::Exporter(QObject *parent)
    : QObject(parent)
    , m_originalVideoFile(0)
    , m_audio(0)
    , m_container(0)
    , m_videoStream(0)
    , m_audioStream(0)
{
}

void Exporter::configure(const QString& fname,
                             VideoFile * vfile,
                             const QList<WtsAudio::BufferAt *>& sequence,
                             WtsAudio * audio,
                             QProgressDialog * progress)
{
    m_filename = fname.toLocal8Bit();
    m_originalVideoFile = vfile;
    m_sequence = sequence;
    m_audio = audio;
    m_progress = progress;
}

void Exporter::initExport()
{
    AVOutputFormat * format = av_guess_format(NULL, m_filename.constData(), NULL);
    if (!format) {
        qWarning() << "Could not deduce output format "
                      "from file extension: using MOV (QuickTime).";
        format = av_guess_format("mov", NULL, NULL);
    }

    TRY_ASSERT_X(format, "Could not find suitable output format");

    m_container = avformat_alloc_context();
    TRY_ASSERT_X(m_container, "Memory error in ffmpeg");
    m_container->oformat = format;
    // apparently this is the normal ffmpeg way to set the filename
    snprintf(m_container->filename,
             sizeof(m_container->filename),
             "%s",
             m_filename.constData());

    if (format->audio_codec != CODEC_ID_NONE)
        initAudioStream(format->audio_codec);
    if (format->video_codec != CODEC_ID_NONE)
        initVideoStream();

    // set the output parameters (must be done even if no parameters)
    TRY_ASSERT_X((av_set_parameters(m_container, NULL) >= 0),
                 "Invalid output format parameters");

    av_dump_format(m_container, 0, m_filename.constData(), 1);

    AVCodec * audioCodec = avcodec_find_encoder(m_audioStream->codec->codec_id);
    TRY_ASSERT_X(audioCodec, "Could not find audio encoder");
    TRY_ASSERT_X((avcodec_open(m_audioStream->codec, audioCodec) >= 0),
                 "Could not open audio encoder");

    AVCodec * videoCodec = avcodec_find_encoder(m_videoStream->codec->codec_id);
    TRY_ASSERT_X(videoCodec, "Video codec not found");
    TRY_ASSERT_X((avcodec_open(m_videoStream->codec, videoCodec) >= 0),
                 "Could not open video codec");

    TRY_ASSERT_X( ( avio_open(&m_container->pb,
                              m_filename.constData(),
                              URL_WRONLY) >= 0 ),
                 QString("Could not open " + m_filename));

}

void Exporter::performExport()
{
    QVector<uint8_t> m_encodedAudio(10000);

    // this is copied from ffmpeg's output-example
    // original comment states that it's an "ugly hack for PCM codecs"
    int mixBufferSize = m_audioStream->codec->frame_size;
    if (m_audioStream->codec->frame_size <= 1) {
        mixBufferSize = m_encodedAudio.size() / m_audioStream->codec->channels;
        switch(m_audioStream->codec->codec_id) {
        case CODEC_ID_PCM_S16LE:
        case CODEC_ID_PCM_S16BE:
        case CODEC_ID_PCM_U16LE:
        case CODEC_ID_PCM_U16BE:
            mixBufferSize >>= 1;
            break;
        default:
            break;
        }
    }

    QVector<int16_t> m_mixBuffer(mixBufferSize * m_audioStream->codec->channels);

    av_write_header(m_container);

    m_originalVideoFile->seek(0);
    m_audio->samplerClear();
    qSort(m_sequence.begin(), m_sequence.end(), WtsAudio::startsBefore);
    QList<WtsAudio::BufferAt *>::iterator sequenceCursor = m_sequence.begin();

    double duration = (double)m_videoStream->duration
            * m_videoStream->time_base.num
            / m_videoStream->time_base.den;
    bool moreVideo = true, moreAudio = true;
    while(moreVideo || moreAudio) {
        double audio_pts = (double)m_audioStream->pts.val
                * m_audioStream->time_base.num
                / m_audioStream->time_base.den;
        double video_pts = (double)m_videoStream->pts.val
                * m_videoStream->time_base.num
                / m_videoStream->time_base.den;

        moreAudio = audio_pts < duration;

        double pts;

        AVPacket packet;
        if ( moreVideo
                && (!moreAudio || (video_pts < audio_pts))
                && (moreVideo = m_originalVideoFile->nextPacket(packet)) ) {
            packet.stream_index = m_videoStream->index;
            av_interleaved_write_frame(m_container, &packet);
            pts = video_pts;
        } else if (moreAudio) {

            av_init_packet(&packet);

            qint64 ms = (qint64)(audio_pts * 1000.0);

            while( sequenceCursor != m_sequence.end()
                  && (*sequenceCursor)->at() <= ms ) {
                m_audio->samplerSchedule(*sequenceCursor);
                sequenceCursor++;
            }

            m_audio->samplerMix( ms, m_mixBuffer);

            packet.size = avcodec_encode_audio(m_audioStream->codec,
                                               m_encodedAudio.data(),
                                               m_encodedAudio.size(),
                                               m_mixBuffer.data());
            if (m_audioStream->codec->coded_frame
                    && ( (uint64_t) m_audioStream->codec->coded_frame->pts
                        != AV_NOPTS_VALUE) )
                packet.pts= av_rescale_q(m_audioStream->codec->coded_frame->pts,
                                         m_audioStream->codec->time_base,
                                         m_audioStream->time_base);
            packet.flags |= AV_PKT_FLAG_KEY;
            packet.stream_index= m_audioStream->index;
            packet.data= m_encodedAudio.data();
            av_interleaved_write_frame(m_container, &packet);

            pts = audio_pts;
        }

        m_progress->setValue(100 * pts / duration);
    }

    av_write_trailer(m_container);
}

void Exporter::run()
{
    try {
        m_progress->setValue(0);

        initExport();
        performExport();
        finishUp();

        m_progress->setValue(100);
    } catch (const AssertFailed& e) {
        qCritical() << e.cMessage();
    }
}

void Exporter::finishUp()
{
    avcodec_close(m_videoStream->codec);
    avcodec_close(m_audioStream->codec);

    /* free the resources */
    for(unsigned i = 0; i < m_container->nb_streams; i++) {
        av_freep(&m_container->streams[i]->codec);
        av_freep(&m_container->streams[i]);
    }

    avio_close(m_container->pb);
    av_free(m_container);
}

void Exporter::initAudioStream(CodecID codec_id)
{
    AVCodecContext * codecContext;

    m_audioStream = av_new_stream(m_container, 1);
    TRY_ASSERT_X(m_audioStream, "Could not alloc stream");

    codecContext = m_audioStream->codec;
    codecContext->codec_id = codec_id;
    codecContext->codec_type = AVMEDIA_TYPE_AUDIO;

    /* put sample parameters */
    codecContext->sample_fmt = AV_SAMPLE_FMT_S16;
    codecContext->bit_rate = 64000;
    codecContext->sample_rate = 44100;
    codecContext->channels = 1;

    // some formats want stream headers to be separate
    if(m_container->oformat->flags & AVFMT_GLOBALHEADER)
        codecContext->flags |= CODEC_FLAG_GLOBAL_HEADER;
}

void Exporter::initVideoStream()
{
    // Video output stream is pretty much a copy of the input video
    m_videoStream = av_new_stream(m_container, 0);
    TRY_ASSERT_X(m_videoStream, "Could not allocate memory");

    const AVStream * oldStream = m_originalVideoFile->stream();
    // we copy some fields but leave other as they were initialized by
    // av_new_stream() above. this way we're sure that no pointers to
    // malloced memory get copied and later freed twice.
    m_videoStream->r_frame_rate = oldStream->r_frame_rate;
    m_videoStream->first_dts = oldStream->first_dts;
    m_videoStream->pts = oldStream->pts;
    m_videoStream->time_base = oldStream->time_base;
    m_videoStream->pts_wrap_bits = oldStream->pts_wrap_bits;
    m_videoStream->discard = oldStream->discard;
    m_videoStream->quality = oldStream->quality;
    m_videoStream->start_time = oldStream->start_time;
    m_videoStream->duration = oldStream->duration;
    m_videoStream->nb_frames = oldStream->nb_frames;
    m_videoStream->disposition = oldStream->disposition;
    m_videoStream->sample_aspect_ratio = oldStream->sample_aspect_ratio;
    m_videoStream->avg_frame_rate = oldStream->avg_frame_rate;
    // we're not sure this makes any difference but just to be nice
    m_videoStream->stream_copy = 1;

    // copy codec from input file
    m_videoStream->codec = avcodec_alloc_context();
    TRY_ASSERT_X(m_videoStream->codec, "Could not allocate memory");
    avcodec_copy_context(m_videoStream->codec, m_originalVideoFile->codec());
    // can't copy mjpeg without this
    m_videoStream->codec->strict_std_compliance = FF_COMPLIANCE_UNOFFICIAL;
    m_videoStream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;

    // otherwise we crash on non-square pixels (first world trouble)
    m_videoStream->codec->sample_aspect_ratio = m_videoStream->sample_aspect_ratio;

}
<commit_msg>error message box on exporter exceptions<commit_after>#include "exporter.h"
#include "videofile.h"

#include <QtGui>
#include <QtDebug>

class AssertFailed {
public:
    AssertFailed(const QString& cond, const QString& file, int line,
                 QString extra = QString())
    {
        m_message = QString("%1:%2: assertion '%3' failed")
                .arg(file).arg(line).arg(cond);

        if (extra.size())
            m_message += ". " + extra + ".";
    }
    QString message() const { return m_message; }
    const char * cMessage() const { return m_message.toLocal8Bit().constData(); }
protected:
    QString m_message;
};

#define TRY_ASSERT(cond) \
    do { if (!cond) { throw AssertFailed(#cond, __FILE__, __LINE__); } } while (0)
#define TRY_ASSERT_X(cond, message) \
    do { if (!cond) { throw AssertFailed(#cond, __FILE__, __LINE__, message); \
    } } while (0)

Exporter::Exporter(QObject *parent)
    : QObject(parent)
    , m_originalVideoFile(0)
    , m_audio(0)
    , m_container(0)
    , m_videoStream(0)
    , m_audioStream(0)
{
}

void Exporter::configure(const QString& fname,
                             VideoFile * vfile,
                             const QList<WtsAudio::BufferAt *>& sequence,
                             WtsAudio * audio,
                             QProgressDialog * progress)
{
    m_filename = fname.toLocal8Bit();
    m_originalVideoFile = vfile;
    m_sequence = sequence;
    m_audio = audio;
    m_progress = progress;
}

void Exporter::initExport()
{
    AVOutputFormat * format = av_guess_format(NULL, m_filename.constData(), NULL);
    if (!format) {
        qWarning() << "Could not deduce output format "
                      "from file extension: using MOV (QuickTime).";
        format = av_guess_format("mov", NULL, NULL);
    }

    TRY_ASSERT_X(format, "Could not find suitable output format");

    m_container = avformat_alloc_context();
    TRY_ASSERT_X(m_container, "Memory error in ffmpeg");
    m_container->oformat = format;
    // apparently this is the normal ffmpeg way to set the filename
    snprintf(m_container->filename,
             sizeof(m_container->filename),
             "%s",
             m_filename.constData());

    if (format->audio_codec != CODEC_ID_NONE)
        initAudioStream(format->audio_codec);
    if (format->video_codec != CODEC_ID_NONE)
        initVideoStream();

    // set the output parameters (must be done even if no parameters)
    TRY_ASSERT_X((av_set_parameters(m_container, NULL) >= 0),
                 "Invalid output format parameters");

    av_dump_format(m_container, 0, m_filename.constData(), 1);

    AVCodec * audioCodec = avcodec_find_encoder(m_audioStream->codec->codec_id);
    TRY_ASSERT_X(audioCodec, "Could not find audio encoder");
    TRY_ASSERT_X((avcodec_open(m_audioStream->codec, audioCodec) >= 0),
                 "Could not open audio encoder");

    AVCodec * videoCodec = avcodec_find_encoder(m_videoStream->codec->codec_id);
    TRY_ASSERT_X(videoCodec, "Video codec not found");
    TRY_ASSERT_X((avcodec_open(m_videoStream->codec, videoCodec) >= 0),
                 "Could not open video codec");

    TRY_ASSERT_X( ( avio_open(&m_container->pb,
                              m_filename.constData(),
                              URL_WRONLY) >= 0 ),
                 QString("Could not open " + m_filename));

}

void Exporter::performExport()
{
    QVector<uint8_t> m_encodedAudio(10000);

    // this is copied from ffmpeg's output-example
    // original comment states that it's an "ugly hack for PCM codecs"
    int mixBufferSize = m_audioStream->codec->frame_size;
    if (m_audioStream->codec->frame_size <= 1) {
        mixBufferSize = m_encodedAudio.size() / m_audioStream->codec->channels;
        switch(m_audioStream->codec->codec_id) {
        case CODEC_ID_PCM_S16LE:
        case CODEC_ID_PCM_S16BE:
        case CODEC_ID_PCM_U16LE:
        case CODEC_ID_PCM_U16BE:
            mixBufferSize >>= 1;
            break;
        default:
            break;
        }
    }

    QVector<int16_t> m_mixBuffer(mixBufferSize * m_audioStream->codec->channels);

    av_write_header(m_container);

    m_originalVideoFile->seek(0);
    m_audio->samplerClear();
    qSort(m_sequence.begin(), m_sequence.end(), WtsAudio::startsBefore);
    QList<WtsAudio::BufferAt *>::iterator sequenceCursor = m_sequence.begin();

    double duration = (double)m_videoStream->duration
            * m_videoStream->time_base.num
            / m_videoStream->time_base.den;
    bool moreVideo = true, moreAudio = true;
    while(moreVideo || moreAudio) {
        double audio_pts = (double)m_audioStream->pts.val
                * m_audioStream->time_base.num
                / m_audioStream->time_base.den;
        double video_pts = (double)m_videoStream->pts.val
                * m_videoStream->time_base.num
                / m_videoStream->time_base.den;

        moreAudio = audio_pts < duration;

        double pts;

        AVPacket packet;
        if ( moreVideo
                && (!moreAudio || (video_pts < audio_pts))
                && (moreVideo = m_originalVideoFile->nextPacket(packet)) ) {
            packet.stream_index = m_videoStream->index;
            av_interleaved_write_frame(m_container, &packet);
            pts = video_pts;
        } else if (moreAudio) {

            av_init_packet(&packet);

            qint64 ms = (qint64)(audio_pts * 1000.0);

            while( sequenceCursor != m_sequence.end()
                  && (*sequenceCursor)->at() <= ms ) {
                m_audio->samplerSchedule(*sequenceCursor);
                sequenceCursor++;
            }

            m_audio->samplerMix( ms, m_mixBuffer);

            packet.size = avcodec_encode_audio(m_audioStream->codec,
                                               m_encodedAudio.data(),
                                               m_encodedAudio.size(),
                                               m_mixBuffer.data());
            if (m_audioStream->codec->coded_frame
                    && ( (uint64_t) m_audioStream->codec->coded_frame->pts
                        != AV_NOPTS_VALUE) )
                packet.pts= av_rescale_q(m_audioStream->codec->coded_frame->pts,
                                         m_audioStream->codec->time_base,
                                         m_audioStream->time_base);
            packet.flags |= AV_PKT_FLAG_KEY;
            packet.stream_index= m_audioStream->index;
            packet.data= m_encodedAudio.data();
            av_interleaved_write_frame(m_container, &packet);

            pts = audio_pts;
        }

        m_progress->setValue(100 * pts / duration);
    }

    av_write_trailer(m_container);
}

void Exporter::run()
{
    try {
        m_progress->setValue(0);

        initExport();
        performExport();
        finishUp();

        m_progress->setValue(100);
    } catch (const AssertFailed& e) {
        qCritical() << e.cMessage();

        m_progress->cancel();

        QMessageBox dialog(m_progress->parentWidget());
        dialog.setText("Fout in exporter");
        dialog.setInformativeText("Iets ging verkeerd tijdens het opslaan van " + m_filename);
        dialog.setDetailedText(e.message());
        dialog.setIcon(QMessageBox::Critical);
        dialog.setWindowModality(Qt::WindowModal);
        dialog.setModal(true);
        dialog.exec();
    }
}

void Exporter::finishUp()
{
    avcodec_close(m_videoStream->codec);
    avcodec_close(m_audioStream->codec);

    /* free the resources */
    for(unsigned i = 0; i < m_container->nb_streams; i++) {
        av_freep(&m_container->streams[i]->codec);
        av_freep(&m_container->streams[i]);
    }

    avio_close(m_container->pb);
    av_free(m_container);
}

void Exporter::initAudioStream(CodecID codec_id)
{
    AVCodecContext * codecContext;

    m_audioStream = av_new_stream(m_container, 1);
    TRY_ASSERT_X(m_audioStream, "Could not alloc stream");

    codecContext = m_audioStream->codec;
    codecContext->codec_id = codec_id;
    codecContext->codec_type = AVMEDIA_TYPE_AUDIO;

    /* put sample parameters */
    codecContext->sample_fmt = AV_SAMPLE_FMT_S16;
    codecContext->bit_rate = 64000;
    codecContext->sample_rate = 44100;
    codecContext->channels = 1;

    // some formats want stream headers to be separate
    if(m_container->oformat->flags & AVFMT_GLOBALHEADER)
        codecContext->flags |= CODEC_FLAG_GLOBAL_HEADER;
}

void Exporter::initVideoStream()
{
    // Video output stream is pretty much a copy of the input video
    m_videoStream = av_new_stream(m_container, 0);
    TRY_ASSERT_X(m_videoStream, "Could not allocate memory");

    const AVStream * oldStream = m_originalVideoFile->stream();
    // we copy some fields but leave other as they were initialized by
    // av_new_stream() above. this way we're sure that no pointers to
    // malloced memory get copied and later freed twice.
    m_videoStream->r_frame_rate = oldStream->r_frame_rate;
    m_videoStream->first_dts = oldStream->first_dts;
    m_videoStream->pts = oldStream->pts;
    m_videoStream->time_base = oldStream->time_base;
    m_videoStream->pts_wrap_bits = oldStream->pts_wrap_bits;
    m_videoStream->discard = oldStream->discard;
    m_videoStream->quality = oldStream->quality;
    m_videoStream->start_time = oldStream->start_time;
    m_videoStream->duration = oldStream->duration;
    m_videoStream->nb_frames = oldStream->nb_frames;
    m_videoStream->disposition = oldStream->disposition;
    m_videoStream->sample_aspect_ratio = oldStream->sample_aspect_ratio;
    m_videoStream->avg_frame_rate = oldStream->avg_frame_rate;
    // we're not sure this makes any difference but just to be nice
    m_videoStream->stream_copy = 1;

    // copy codec from input file
    m_videoStream->codec = avcodec_alloc_context();
    TRY_ASSERT_X(m_videoStream->codec, "Could not allocate memory");
    avcodec_copy_context(m_videoStream->codec, m_originalVideoFile->codec());
    // can't copy mjpeg without this
    m_videoStream->codec->strict_std_compliance = FF_COMPLIANCE_UNOFFICIAL;
    m_videoStream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;

    // otherwise we crash on non-square pixels (first world trouble)
    m_videoStream->codec->sample_aspect_ratio = m_videoStream->sample_aspect_ratio;

}
<|endoftext|>


<commit_before>

#include <memory>
#include <lv2/lv2plug.in/ns/ext/midi/midi.h>
#include "tests.hpp"

class Atom : public TestFixutre
{
  CPPUNIT_TEST_SUITE (Atom);
  CPPUNIT_TEST (atom);
  CPPUNIT_TEST (sequence);
  CPPUNIT_TEST_SUITE_END();

protected:
    lvtk::URIDirectory urids;
    lvtk::Forge forge;
    std::unique_ptr<uint8_t[]> buffer;
    uint32_t buffer_size = 4096 * 2;
public:
    void setUp()
    {
        buffer.reset (new uint8_t [buffer_size]);
        clear_buffer();
        forge.init ((LV2_URID_Map*) urids.get_map_feature()->data);
    }

    void clear_buffer() {
        memset (buffer.get(), 0, (size_t) buffer_size);
    }

    template<class T>
    T* buffer_as() const { return (T*) buffer.get(); }

protected:
    void atom() {
        for (uint32_t sz = 2; sz < 2048; sz *= 2)
            CPPUNIT_ASSERT_EQUAL (lvtk::Atom::pad_size (sz), lv2_atom_pad_size (sz));

        lvtk::Atom atom;
        CPPUNIT_ASSERT_EQUAL (atom.is_null(), true);
        CPPUNIT_ASSERT_EQUAL ((bool) atom, false);
        CPPUNIT_ASSERT_EQUAL (atom.c_obj(), (const LV2_Atom*) nullptr);

        const LV2_Atom_Float afloat = { { sizeof(float), 1 }, 100.f };
        atom = lvtk::Atom ((void*) &afloat);
        CPPUNIT_ASSERT (atom.has_type_and_equals (1, 100.f));
        CPPUNIT_ASSERT (atom.total_size() == sizeof(float) + sizeof (*atom.c_obj()));
        CPPUNIT_ASSERT (atom.size() == sizeof (float));
        CPPUNIT_ASSERT (atom.type() == 1);

        const LV2_Atom_Float bfloat = { { sizeof(float), 1 }, 101.f };
        lvtk::Atom batom ((void*) &bfloat);
        CPPUNIT_ASSERT (atom != batom);
        batom = atom;
        CPPUNIT_ASSERT (atom == batom);
    }

    void sequence() {
        clear_buffer();
        auto* const cseq = buffer_as<LV2_Atom_Sequence>();
        cseq->atom.type  = urids.map (LV2_ATOM__Sequence);
        cseq->atom.size  = sizeof (LV2_Atom_Sequence_Body);
        cseq->body.unit  = urids.map (LV2_ATOM__frameTime);
        cseq->body.pad   = 0;

        lvtk::Sequence seq (cseq);
        CPPUNIT_ASSERT (seq.size() == sizeof (LV2_Atom_Sequence_Body));
        CPPUNIT_ASSERT (seq.unit() == urids.map (LV2_ATOM__frameTime));

        uint8_t evbuf [sizeof (lvtk::AtomEvent) + 3];
        lvtk::AtomEvent* const event = (lvtk::AtomEvent*) evbuf;
        event->time.frames = 0;
        event->body.type = urids.map (LV2_MIDI__MidiEvent);
        event->body.size = 3;
        // note on
        ((uint8_t*)LV2_ATOM_BODY (&event->body))[0] = 0x80;
        ((uint8_t*)LV2_ATOM_BODY (&event->body))[1] = 0x7f;
        ((uint8_t*)LV2_ATOM_BODY (&event->body))[2] = 0x40;

        const uint32_t nev = 20;
        for (uint32_t i = 0; i < nev; ++i) {
            seq.append (*event);
            event->time.frames += 20;
        }

        CPPUNIT_ASSERT_EQUAL (seq.size(),
            (nev * lv2_atom_pad_size ((uint32_t) sizeof (lvtk::AtomEvent) + 3)) + (uint32_t)sizeof (LV2_Atom_Sequence_Body));

        uint32_t cnt = 0;
        int64_t frame = 0;
        for (const auto& ev : seq) {
            CPPUNIT_ASSERT_EQUAL (urids.map (LV2_MIDI__MidiEvent), ev.body.type);
            CPPUNIT_ASSERT_EQUAL ((uint32_t) 3, ev.body.size);
            CPPUNIT_ASSERT_EQUAL (frame, ev.time.frames);
            frame += 20;
            ++cnt;
        }

        CPPUNIT_ASSERT_EQUAL (nev, cnt);

        // same test but with LV2 macro
        cnt = 0;
        frame = 0;
        LV2_ATOM_SEQUENCE_FOREACH (seq.c_obj(), iter) {
            auto& ev = *iter;
            CPPUNIT_ASSERT_EQUAL (urids.map (LV2_MIDI__MidiEvent), ev.body.type);
            CPPUNIT_ASSERT_EQUAL ((uint32_t)3, ev.body.size);
            CPPUNIT_ASSERT_EQUAL (frame, ev.time.frames);
            frame += 20;
            ++cnt;
        }

        CPPUNIT_ASSERT_EQUAL (nev, cnt);

        event->body.size = 3;
        event->body.type = 111;
        event->time.frames = 10;
        seq.insert (*event);
        cnt = 0;
        frame = 0;
        for (const auto& ev : seq) {
            if (cnt == 1) {
                CPPUNIT_ASSERT_EQUAL ((uint32_t) 111, ev.body.type);
                CPPUNIT_ASSERT_EQUAL ((int64_t) 10, ev.time.frames);
                frame += 10;
            } else {
                CPPUNIT_ASSERT_EQUAL (urids.map (LV2_MIDI__MidiEvent), ev.body.type);
                CPPUNIT_ASSERT_EQUAL ((uint32_t)3, ev.body.size);
                CPPUNIT_ASSERT_EQUAL (frame, ev.time.frames);
                frame += cnt == 0 ? 10 : 20;
            }
            ++cnt;
        }

        CPPUNIT_ASSERT_EQUAL (nev + 1, cnt);
    }
};

CPPUNIT_TEST_SUITE_REGISTRATION (Atom);
<commit_msg>Use real mapped URIDs in tests<commit_after>

#include <memory>
#include <lv2/lv2plug.in/ns/ext/midi/midi.h>
#include "tests.hpp"

class Atom : public TestFixutre
{
  CPPUNIT_TEST_SUITE (Atom);
  CPPUNIT_TEST (atom);
  CPPUNIT_TEST (sequence);
  CPPUNIT_TEST_SUITE_END();

protected:
    lvtk::URIDirectory urids;
    lvtk::Forge forge;
    std::unique_ptr<uint8_t[]> buffer;
    uint32_t buffer_size = 4096 * 2;
public:
    void setUp()
    {
        buffer.reset (new uint8_t [buffer_size]);
        clear_buffer();
        forge.init ((LV2_URID_Map*) urids.get_map_feature()->data);
    }

    void clear_buffer() {
        memset (buffer.get(), 0, (size_t) buffer_size);
    }

    template<class T>
    T* buffer_as() const { return (T*) buffer.get(); }

protected:
    void atom() {
        for (uint32_t sz = 2; sz < 2048; sz *= 2)
            CPPUNIT_ASSERT_EQUAL (lvtk::Atom::pad_size (sz), lv2_atom_pad_size (sz));

        lvtk::Atom atom;
        CPPUNIT_ASSERT_EQUAL (atom.is_null(), true);
        CPPUNIT_ASSERT_EQUAL ((bool) atom, false);
        CPPUNIT_ASSERT_EQUAL (atom.c_obj(), (const LV2_Atom*) nullptr);

        const LV2_Atom_Float afloat = { { sizeof(float), urids.map(LV2_ATOM__Float) }, 100.f };
        atom = lvtk::Atom ((void*) &afloat);
        CPPUNIT_ASSERT (atom.has_type_and_equals (urids.map(LV2_ATOM__Float), 100.f));
        CPPUNIT_ASSERT (atom.total_size() == sizeof(float) + sizeof (*atom.c_obj()));
        CPPUNIT_ASSERT (atom.size() == sizeof (float));
        CPPUNIT_ASSERT (atom.type() == urids.map(LV2_ATOM__Float));

        const LV2_Atom_Float bfloat = { { sizeof(float), urids.map(LV2_ATOM__Float) }, 101.f };
        lvtk::Atom batom ((void*) &bfloat);
        CPPUNIT_ASSERT (atom != batom);
        batom = atom;
        CPPUNIT_ASSERT (atom == batom);
    }

    void sequence() {
        clear_buffer();
        auto* const cseq = buffer_as<LV2_Atom_Sequence>();
        cseq->atom.type  = urids.map (LV2_ATOM__Sequence);
        cseq->atom.size  = sizeof (LV2_Atom_Sequence_Body);
        cseq->body.unit  = urids.map (LV2_ATOM__frameTime);
        cseq->body.pad   = 0;

        lvtk::Sequence seq (cseq);
        CPPUNIT_ASSERT (seq.size() == sizeof (LV2_Atom_Sequence_Body));
        CPPUNIT_ASSERT (seq.unit() == urids.map (LV2_ATOM__frameTime));

        uint8_t evbuf [sizeof (lvtk::AtomEvent) + 3];
        lvtk::AtomEvent* const event = (lvtk::AtomEvent*) evbuf;
        event->time.frames = 0;
        event->body.type = urids.map (LV2_MIDI__MidiEvent);
        event->body.size = 3;
        // note on
        ((uint8_t*)LV2_ATOM_BODY (&event->body))[0] = 0x80;
        ((uint8_t*)LV2_ATOM_BODY (&event->body))[1] = 0x7f;
        ((uint8_t*)LV2_ATOM_BODY (&event->body))[2] = 0x40;

        const uint32_t nev = 20;
        for (uint32_t i = 0; i < nev; ++i) {
            seq.append (*event);
            event->time.frames += 20;
        }

        CPPUNIT_ASSERT_EQUAL (seq.size(),
            (nev * lv2_atom_pad_size ((uint32_t) sizeof (lvtk::AtomEvent) + 3)) + (uint32_t)sizeof (LV2_Atom_Sequence_Body));

        uint32_t cnt = 0;
        int64_t frame = 0;
        for (const auto& ev : seq) {
            CPPUNIT_ASSERT_EQUAL (urids.map (LV2_MIDI__MidiEvent), ev.body.type);
            CPPUNIT_ASSERT_EQUAL ((uint32_t) 3, ev.body.size);
            CPPUNIT_ASSERT_EQUAL (frame, ev.time.frames);
            frame += 20;
            ++cnt;
        }

        CPPUNIT_ASSERT_EQUAL (nev, cnt);

        // same test but with LV2 macro
        cnt = 0;
        frame = 0;
        LV2_ATOM_SEQUENCE_FOREACH (seq.c_obj(), iter) {
            auto& ev = *iter;
            CPPUNIT_ASSERT_EQUAL (urids.map (LV2_MIDI__MidiEvent), ev.body.type);
            CPPUNIT_ASSERT_EQUAL ((uint32_t)3, ev.body.size);
            CPPUNIT_ASSERT_EQUAL (frame, ev.time.frames);
            frame += 20;
            ++cnt;
        }

        CPPUNIT_ASSERT_EQUAL (nev, cnt);

        event->body.size = 3;
        event->body.type = 111;
        event->time.frames = 10;
        seq.insert (*event);
        cnt = 0;
        frame = 0;
        for (const auto& ev : seq) {
            if (cnt == 1) {
                CPPUNIT_ASSERT_EQUAL ((uint32_t) 111, ev.body.type);
                CPPUNIT_ASSERT_EQUAL ((int64_t) 10, ev.time.frames);
                frame += 10;
            } else {
                CPPUNIT_ASSERT_EQUAL (urids.map (LV2_MIDI__MidiEvent), ev.body.type);
                CPPUNIT_ASSERT_EQUAL ((uint32_t)3, ev.body.size);
                CPPUNIT_ASSERT_EQUAL (frame, ev.time.frames);
                frame += cnt == 0 ? 10 : 20;
            }
            ++cnt;
        }

        CPPUNIT_ASSERT_EQUAL (nev + 1, cnt);
    }
};

CPPUNIT_TEST_SUITE_REGISTRATION (Atom);
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkGradientShader.h"
#include "SkPatchUtils.h"
#include "SkPath.h"

static sk_sp<SkShader> make_shader() {
    const SkColor colors[] = {
        SK_ColorRED, SK_ColorCYAN, SK_ColorGREEN, SK_ColorWHITE, SK_ColorMAGENTA, SK_ColorBLUE,
        SK_ColorYELLOW,
    };
    const SkPoint pts[] = { { 100.f / 4.f, 0.f }, { 3.f * 100.f / 4.f, 100.f } };

    return SkGradientShader::MakeLinear(pts, colors, nullptr, SK_ARRAY_COUNT(colors),
                                        SkShader::kMirror_TileMode);
}

static void draw_control_points(SkCanvas* canvas, const SkPoint cubics[12]) {
    //draw control points
    SkPaint paint;
    SkPoint bottom[SkPatchUtils::kNumPtsCubic];
    SkPatchUtils::GetBottomCubic(cubics, bottom);
    SkPoint top[SkPatchUtils::kNumPtsCubic];
    SkPatchUtils::GetTopCubic(cubics, top);
    SkPoint left[SkPatchUtils::kNumPtsCubic];
    SkPatchUtils::GetLeftCubic(cubics, left);
    SkPoint right[SkPatchUtils::kNumPtsCubic];
    SkPatchUtils::GetRightCubic(cubics, right);

    paint.setColor(SK_ColorBLACK);
    paint.setStrokeWidth(0.5f);
    SkPoint corners[4] = { bottom[0], bottom[3], top[0], top[3] };
    canvas->drawPoints(SkCanvas::kLines_PointMode, 4, bottom, paint);
    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, bottom + 1, paint);
    canvas->drawPoints(SkCanvas::kLines_PointMode, 4, top, paint);
    canvas->drawPoints(SkCanvas::kLines_PointMode, 4, left, paint);
    canvas->drawPoints(SkCanvas::kLines_PointMode, 4, right, paint);

    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, top + 1, paint);
    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, left + 1, paint);
    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, right + 1, paint);

    paint.setStrokeWidth(2);

    paint.setColor(SK_ColorRED);
    canvas->drawPoints(SkCanvas::kPoints_PointMode, 4, corners, paint);

    paint.setColor(SK_ColorBLUE);
    canvas->drawPoints(SkCanvas::kPoints_PointMode, 2, bottom + 1, paint);

    paint.setColor(SK_ColorCYAN);
    canvas->drawPoints(SkCanvas::kPoints_PointMode, 2, top + 1, paint);

    paint.setColor(SK_ColorYELLOW);
    canvas->drawPoints(SkCanvas::kPoints_PointMode, 2, left + 1, paint);

    paint.setColor(SK_ColorGREEN);
    canvas->drawPoints(SkCanvas::kPoints_PointMode, 2, right + 1, paint);
}

// The order of the colors and points is clockwise starting at upper-left corner.
const SkPoint gCubics[SkPatchUtils::kNumCtrlPts] = {
    //top points
    {100,100},{150,50},{250,150}, {300,100},
    //right points
    {250, 150},{350,250},
    //bottom points
    {300,300},{250,250},{150,350},{100,300},
    //left points
    {50,250},{150,150}
};

const SkPoint gTexCoords[SkPatchUtils::kNumCorners] = {
    {0.0f, 0.0f}, {100.0f, 0.0f}, {100.0f,100.0f}, {0.0f, 100.0f}
};

static void dopatch(SkCanvas* canvas, const SkColor colors[]) {
    SkPaint paint;

    const SkBlendMode modes[] = {
        SkBlendMode::kSrc,
        SkBlendMode::kDst,
        SkBlendMode::kModulate,
    };

    sk_sp<SkShader> shader(make_shader());

    canvas->save();
    for (int y = 0; y < 3; y++) {
        for (int x = 0; x < 4; x++) {
            canvas->save();
            canvas->translate(x * 350.0f, y * 350.0f);
            switch (x) {
                case 0:
                    canvas->drawPatch(gCubics, nullptr, nullptr, modes[y], paint);
                    break;
                case 1:
                    canvas->drawPatch(gCubics, colors, nullptr, modes[y], paint);
                    break;
                case 2:
                    paint.setShader(shader);
                    canvas->drawPatch(gCubics, nullptr, gTexCoords, modes[y], paint);
                    paint.setShader(nullptr);
                    break;
                case 3:
                    paint.setShader(shader);
                    canvas->drawPatch(gCubics, colors, gTexCoords, modes[y], paint);
                    paint.setShader(nullptr);
                    break;
                default:
                    break;
            }

            draw_control_points(canvas, gCubics);
            canvas->restore();
        }
    }
    canvas->restore();
}

DEF_SIMPLE_GM(patch_primitive, canvas, 1500, 1100) {
    const SkColor colors[SkPatchUtils::kNumCorners] = {
        SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorCYAN
    };
    dopatch(canvas, colors);
}
DEF_SIMPLE_GM(patch_alpha, canvas, 1500, 1100) {
    const SkColor colors[SkPatchUtils::kNumCorners] = {
        SK_ColorRED, 0x0000FF00, SK_ColorBLUE, 0x00FF00FF,
    };
    dopatch(canvas, colors);
}

// These two should look the same (one patch, one simple path)
DEF_SIMPLE_GM(patch_alpha_test, canvas, 550, 250) {
    canvas->translate(-75, -75);

    const SkColor colors[SkPatchUtils::kNumCorners] = {
        0x80FF0000, 0x80FF0000, 0x80FF0000, 0x80FF0000,
    };
    SkPaint paint;
    canvas->drawPatch(gCubics, colors, nullptr, SkBlendMode::kModulate, paint);

    canvas->translate(300, 0);

    SkPath path;
    path.moveTo(gCubics[0]);
    path.cubicTo(gCubics[ 1], gCubics[ 2], gCubics[ 3]);
    path.cubicTo(gCubics[ 4], gCubics[ 5], gCubics[ 6]);
    path.cubicTo(gCubics[ 7], gCubics[ 8], gCubics[ 9]);
    path.cubicTo(gCubics[10], gCubics[11], gCubics[ 0]);
    paint.setColor(colors[0]);
    canvas->drawPath(path, paint);
}

<commit_msg>Roll external/skia d17b4a678..d36968bd9 (1 commits)<commit_after>/*
 * Copyright 2014 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkGradientShader.h"
#include "SkImage.h"
#include "SkPatchUtils.h"
#include "SkPath.h"

static sk_sp<SkShader> make_shader() {
    const SkColor colors[] = {
        SK_ColorRED, SK_ColorCYAN, SK_ColorGREEN, SK_ColorWHITE, SK_ColorMAGENTA, SK_ColorBLUE,
        SK_ColorYELLOW,
    };
    const SkPoint pts[] = { { 100.f / 4.f, 0.f }, { 3.f * 100.f / 4.f, 100.f } };

    return SkGradientShader::MakeLinear(pts, colors, nullptr, SK_ARRAY_COUNT(colors),
                                        SkShader::kMirror_TileMode);
}

static void draw_control_points(SkCanvas* canvas, const SkPoint cubics[12]) {
    //draw control points
    SkPaint paint;
    SkPoint bottom[SkPatchUtils::kNumPtsCubic];
    SkPatchUtils::GetBottomCubic(cubics, bottom);
    SkPoint top[SkPatchUtils::kNumPtsCubic];
    SkPatchUtils::GetTopCubic(cubics, top);
    SkPoint left[SkPatchUtils::kNumPtsCubic];
    SkPatchUtils::GetLeftCubic(cubics, left);
    SkPoint right[SkPatchUtils::kNumPtsCubic];
    SkPatchUtils::GetRightCubic(cubics, right);

    paint.setColor(SK_ColorBLACK);
    paint.setStrokeWidth(0.5f);
    SkPoint corners[4] = { bottom[0], bottom[3], top[0], top[3] };
    canvas->drawPoints(SkCanvas::kLines_PointMode, 4, bottom, paint);
    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, bottom + 1, paint);
    canvas->drawPoints(SkCanvas::kLines_PointMode, 4, top, paint);
    canvas->drawPoints(SkCanvas::kLines_PointMode, 4, left, paint);
    canvas->drawPoints(SkCanvas::kLines_PointMode, 4, right, paint);

    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, top + 1, paint);
    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, left + 1, paint);
    canvas->drawPoints(SkCanvas::kLines_PointMode, 2, right + 1, paint);

    paint.setStrokeWidth(2);

    paint.setColor(SK_ColorRED);
    canvas->drawPoints(SkCanvas::kPoints_PointMode, 4, corners, paint);

    paint.setColor(SK_ColorBLUE);
    canvas->drawPoints(SkCanvas::kPoints_PointMode, 2, bottom + 1, paint);

    paint.setColor(SK_ColorCYAN);
    canvas->drawPoints(SkCanvas::kPoints_PointMode, 2, top + 1, paint);

    paint.setColor(SK_ColorYELLOW);
    canvas->drawPoints(SkCanvas::kPoints_PointMode, 2, left + 1, paint);

    paint.setColor(SK_ColorGREEN);
    canvas->drawPoints(SkCanvas::kPoints_PointMode, 2, right + 1, paint);
}

// The order of the colors and points is clockwise starting at upper-left corner.
const SkPoint gCubics[SkPatchUtils::kNumCtrlPts] = {
    //top points
    {100,100},{150,50},{250,150}, {300,100},
    //right points
    {250, 150},{350,250},
    //bottom points
    {300,300},{250,250},{150,350},{100,300},
    //left points
    {50,250},{150,150}
};

const SkPoint gTexCoords[SkPatchUtils::kNumCorners] = {
    {0.0f, 0.0f}, {100.0f, 0.0f}, {100.0f,100.0f}, {0.0f, 100.0f}
};

static void dopatch(SkCanvas* canvas, const SkColor colors[], sk_sp<SkImage> img = nullptr) {
    SkPaint paint;

    const SkBlendMode modes[] = {
        SkBlendMode::kSrc,
        SkBlendMode::kDst,
        SkBlendMode::kModulate,
    };

    SkPoint texStorage[4];
    const SkPoint* tex = gTexCoords;

    sk_sp<SkShader> shader;
    if (img) {
        SkScalar w = img->width();
        SkScalar h = img->height();
        shader = img->makeShader(SkShader::kClamp_TileMode, SkShader::kClamp_TileMode);
        texStorage[0].set(0, 0);
        texStorage[1].set(w, 0);
        texStorage[2].set(w, h);
        texStorage[3].set(0, h);
        tex = texStorage;
    } else {
        shader = make_shader();
    }

    canvas->save();
    for (int y = 0; y < 3; y++) {
        for (int x = 0; x < 4; x++) {
            canvas->save();
            canvas->translate(x * 350.0f, y * 350.0f);
            switch (x) {
                case 0:
                    canvas->drawPatch(gCubics, nullptr, nullptr, modes[y], paint);
                    break;
                case 1:
                    canvas->drawPatch(gCubics, colors, nullptr, modes[y], paint);
                    break;
                case 2:
                    paint.setShader(shader);
                    canvas->drawPatch(gCubics, nullptr, tex, modes[y], paint);
                    paint.setShader(nullptr);
                    break;
                case 3:
                    paint.setShader(shader);
                    canvas->drawPatch(gCubics, colors, tex, modes[y], paint);
                    paint.setShader(nullptr);
                    break;
                default:
                    break;
            }

            draw_control_points(canvas, gCubics);
            canvas->restore();
        }
    }
    canvas->restore();
}

DEF_SIMPLE_GM(patch_primitive, canvas, 1500, 1100) {
    const SkColor colors[SkPatchUtils::kNumCorners] = {
        SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorCYAN
    };
    dopatch(canvas, colors);
}
#include "Resources.h"
DEF_SIMPLE_GM(patch_image, canvas, 1500, 1100) {
    const SkColor colors[SkPatchUtils::kNumCorners] = {
        SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorCYAN
    };
    dopatch(canvas, colors, GetResourceAsImage("mandrill_128.png"));
}
DEF_SIMPLE_GM(patch_alpha, canvas, 1500, 1100) {
    const SkColor colors[SkPatchUtils::kNumCorners] = {
        SK_ColorRED, 0x0000FF00, SK_ColorBLUE, 0x00FF00FF,
    };
    dopatch(canvas, colors);
}

// These two should look the same (one patch, one simple path)
DEF_SIMPLE_GM(patch_alpha_test, canvas, 550, 250) {
    canvas->translate(-75, -75);

    const SkColor colors[SkPatchUtils::kNumCorners] = {
        0x80FF0000, 0x80FF0000, 0x80FF0000, 0x80FF0000,
    };
    SkPaint paint;
    canvas->drawPatch(gCubics, colors, nullptr, SkBlendMode::kModulate, paint);

    canvas->translate(300, 0);

    SkPath path;
    path.moveTo(gCubics[0]);
    path.cubicTo(gCubics[ 1], gCubics[ 2], gCubics[ 3]);
    path.cubicTo(gCubics[ 4], gCubics[ 5], gCubics[ 6]);
    path.cubicTo(gCubics[ 7], gCubics[ 8], gCubics[ 9]);
    path.cubicTo(gCubics[10], gCubics[11], gCubics[ 0]);
    paint.setColor(colors[0]);
    canvas->drawPath(path, paint);
}

<|endoftext|>


<commit_before>#include <matrix.hpp>
#include <catch.hpp>
#include <iostream>

SCENARIO ("init", "[init]")
{
  BinaryTree<int> tree;
  REQUIRE(tree.root_() == nullptr);
}

SCENARIO ("output", "[output]")
{
  BinaryTree<int> tree;
  tree.insertNode(1);
  REQUIRE( std::cout << tree );
}

SCENARIO("find", "[find]")
  {
    BinaryTree<int> tree;
    tree.insertNode(2);
    tree.insertNode(3);
    REQUIRE(tree.findNode(3, tree.root_()) != nullptr);
    REQUIRE(tree.findNode(3, tree.root_())->data == 3);
  }

SCENARIO("insert", "[insert]")
{
  BinaryTree<int> tree;
  tree.insertNode(4);
  REQUIRE(tree.findNode(4, tree.root_())->data == 4);
}

SCENARIO("remove", "[remove]")
{
  BinaryTree<int> tree;
  tree.insertNode(1);
  tree.insertNode(2);
  tree.insertNode(3);
  tree.deleteValue(1);
  REQUIRE(tree.findNode(1, tree.root_())== nullptr);
  REQUIRE(tree.findNode(2, tree.root_())== tree.root_());
  REQUIRE(tree.root_() != nullptr);
}

SCENARIO("delete", "[delete]")
{
  BinaryTree<int> tree;
  tree.insertNode(1);
  tree.insertNode(2);
  tree.deleteValue(2);
  REQUIRE(tree.getCount() == 1);
}

<commit_msg>Create init.cpp<commit_after>#include <matrix.hpp>
#include <catch.hpp>
#include <iostream>

SCENARIO ("init", "[init]")
{
  BinaryTree<int> tree;
  REQUIRE(tree.root_() == nullptr);
}

SCENARIO ("output", "[output]")
{
  BinaryTree<int> tree;
  tree.insertNode(1);
  REQUIRE( std::cout << tree );
}

SCENARIO("find", "[find]")
  {
    BinaryTree<int> tree;
    tree.insertNode(2);
    tree.insertNode(3);
    REQUIRE(tree.findNode(3, tree.root_()) != nullptr);
    REQUIRE(tree.findNode(3, tree.root_())->data == 3);
  }

SCENARIO("insert", "[insert]")
{
  BinaryTree<int> tree;
  tree.insertNode(4);
  REQUIRE(tree.findNode(4, tree.root_())->data == 4);
}

SCENARIO("remove", "[remove]")
{
  BinaryTree<int> tree;
  tree.insertNode(1);
  tree.insertNode(2);
  tree.insertNode(3);
  tree.deleteValue(1);
  REQUIRE(tree.findNode(1, tree.root_())== nullptr);
  REQUIRE(tree.findNode(2, tree.root_())== tree.root_());
  REQUIRE(tree.root_() != nullptr);
}

SCENARIO("removea", "[removea]")
{
  BinaryTree<int> tree;
  tree.insertNode(3);
  tree.insertNode(2);
  tree.insertNode(1);
  tree.insertNode(5);
  tree.insertNode(4);
  tree.insertNode(6);
  tree.deleteValue(3);
  REQUIRE(tree.findNode(3, tree.root_())== nullptr);
  REQUIRE(tree.findNode(5, tree.root_())== tree.root_());
  REQUIRE(tree.root_() != nullptr);
}

SCENARIO("delete", "[delete]")
{
  BinaryTree<int> tree;
  tree.insertNode(1);
  tree.insertNode(2);
  tree.deleteValue(2);
  REQUIRE(tree.getCount() == 1);
}

<|endoftext|>


<commit_before>#include <BinaryTree.hpp>
#include <catch.hpp>

SCENARIO ("init", "[init]")
{
  BinaryTree<int> obj;
  REQUIRE(obj.root_() == nullptr);
}

SCENARIO ("output to cout", "<<")
{
  BinaryTree<int> tree;
  tree.insert_node(3);
  REQUIRE( std::cout << tree );
}

SCENARIO("find_node", "[find_node]")
  {
    BinaryTree<int> obj;
    obj.insert_node(4);
    obj.insert_node(2);
    REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
    REQUIRE(obj.find_node(2, obj.root_())->data == 2);
  }

SCENARIO("insert", "[insert]")
{
  BinaryTree<int> obj;
  obj.insert_node(3);
  REQUIRE(obj.find_node(3, obj.root_())->data == 3);
}

SCENARIO("removeElement", "[remEl]")
{
  BinaryTree<int> obj;
  obj.insert_node(1);
  obj.insert_node(2);
  obj.insert_node(3);
  obj.remove_element(1);
  REQUIRE(obj.find_node(1, obj.root_())== nullptr);
  REQUIRE(obj.find_node(2, obj.root_())== obj.root_());
  REQUIRE(obj.root_() != nullptr);
}
<commit_msg>Update init.cpp<commit_after>#include <BinaryTree.hpp>
#include <catch.hpp>

SCENARIO ("init", "[init]")
{
  BinaryTree<int> obj;
  REQUIRE(obj.root_() == nullptr);
}

SCENARIO ("output to cout", "<<")
{
  BinaryTree<int> tree;
  tree.insert_node(3);
  REQUIRE( std::cout << tree );
}

SCENARIO("find_node", "[find_node]")
  {
    BinaryTree<int> obj;
    obj.insert_node(4);
    obj.insert_node(2);
    REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
    REQUIRE(obj.find_node(2, obj.root_())->data == 2);
  }

SCENARIO("insert", "[insert]")
{
  BinaryTree<int> obj;
  obj.insert_node(3);
  REQUIRE(obj.find_node(3, obj.root_())->data == 3);
}

SCENARIO("removeElement", "[remEl]")
{
  BinaryTree<int> obj;
  obj.insert_node(1);
  obj.insert_node(2);
  obj.insert_node(3);
  obj.remove_element(1);
  REQUIRE(obj.find_node(1, obj.root_())== nullptr);
  REQUIRE(obj.find_node(2, obj.root_())== obj.root_());
  REQUIRE(obj.root_() != nullptr);
  REQUIRE(test.get_count() == 2);
}
<|endoftext|>


<commit_before>#include <tree.h>
#include <catch.hpp>
#include <fstream>

SCENARIO ("init", "[init]")

{

  Tree<int> test;

  REQUIRE(test.root_() == nullptr);

  REQUIRE(test.get_count() == 0);

}

SCENARIO("insert", "[init]")

{

  Tree<int> test;

  test.insnode(5);

  REQUIRE(test.get_count() == 1);

  REQUIRE(test.find_node(5, test.root_())->key == 5);

}

SCENARIO("find_node", "[init]")

{

  Tree<int> test;

  test.insnode(4);

  REQUIRE(test.find_node(4, test.root_()) != nullptr);

  REQUIRE(test.find_node(4, test.root_())->key == 4);

}

SCENARIO("get root", "[init]")

{

  Tree<int> test;

  test.insnode(4);

  REQUIRE(test.root_() != 0);

}

SCENARIO("insert equal elements", "[insert]")

 {

   Tree<int> test;

   test.insnode(4);

   test.insnode(4);

   REQUIRE(test.get_count() == 1);

 }

SCENARIO ("read/write", "[init]")

{

  Tree<int> test1;
    std::ofstream& file1 = std::open("file2.txt", std::out);
    bool isCatched = false;
  try
    {
  test1.write(file1);

    }// test1.write("~,  , *"); //

    catch(bool isCatched)
    {
      isCatched = true;
    }

  REQUIRE(isCatched == false);

  Tree<int> test2;

  test2.read("file2.txt");

  REQUIRE(test2.find_node(4, test2.root_())!= nullptr);

  REQUIRE(test2.find_node(3, test2.root_())!= nullptr);

  REQUIRE(test1.get_count() == test2.get_count());

}

SCENARIO("deleteX")

{

  Tree<int> test;

  test.insnode(6);

  test.insnode(7);

  test.insnode(9);

  test.deleteVal(6);

  test.deleteVal(9);

  REQUIRE(test.find_node(9, test.root_())== nullptr);

  REQUIRE(test.find_node(7, test.root_())== test.root_());

  REQUIRE(test.root_() != nullptr);

  REQUIRE(test.get_count() == 1);

}
<commit_msg>Update init.cpp<commit_after>#include <tree.h>
#include <catch.hpp>
#include <fstream>

SCENARIO ("init", "[init]")

{

  Tree<int> test;

  REQUIRE(test.root_() == nullptr);

  REQUIRE(test.get_count() == 0);

}

SCENARIO("insert", "[init]")

{

  Tree<int> test;

  test.insnode(5);

  REQUIRE(test.get_count() == 1);

  REQUIRE(test.find_node(5, test.root_())->key == 5);

}

SCENARIO("find_node", "[init]")

{

  Tree<int> test;

  test.insnode(4);

  REQUIRE(test.find_node(4, test.root_()) != nullptr);

  REQUIRE(test.find_node(4, test.root_())->key == 4);

}

SCENARIO("get root", "[init]")

{

  Tree<int> test;

  test.insnode(4);

  REQUIRE(test.root_() != 0);

}

SCENARIO("insert equal elements", "[insert]")

 {

   Tree<int> test;

   test.insnode(4);

   test.insnode(4);

   REQUIRE(test.get_count() == 1);

 }

SCENARIO ("read/write", "[init]")

{

  Tree<int> test1;
    std::ofstream& file1 = std::fstream::open("file2.txt", std::out);
    bool isCatched = false;
  try
    {
  test1.write(file1);

    }// test1.write("~,  , *"); //

    catch(bool isCatched)
    {
      isCatched = true;
    }

  REQUIRE(isCatched == false);

  Tree<int> test2;

  test2.read("file2.txt");

  REQUIRE(test2.find_node(4, test2.root_())!= nullptr);

  REQUIRE(test2.find_node(3, test2.root_())!= nullptr);

  REQUIRE(test1.get_count() == test2.get_count());

}

SCENARIO("deleteX")

{

  Tree<int> test;

  test.insnode(6);

  test.insnode(7);

  test.insnode(9);

  test.deleteVal(6);

  test.deleteVal(9);

  REQUIRE(test.find_node(9, test.root_())== nullptr);

  REQUIRE(test.find_node(7, test.root_())== test.root_());

  REQUIRE(test.root_() != nullptr);

  REQUIRE(test.get_count() == 1);

}
<|endoftext|>


<commit_before>#include "catch.hpp"
#include <iostream>
#include "Database_Creator.hpp"
#include "Database_Sorter.hpp"

person readPerson(std::string file_name, size_t index) {
	person result;
	std::ifstream file(file_name);
	for (size_t i = 0; i < index + 1; i++) {
		file >> result;
	}
	file.close();
	return result;
}
/*bool isALessThanB(char A, char B, bool is_capital) {
	std::string alphabet;
	if (is_capital) {
		alphabet = " АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
	}
	else {
		alphabet = " абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
	}
	size_t A_i;
	size_t B_i;
	for (size_t i = 0; i < alphabet.size(); i++) {
		if (alphabet[i] == A) {
			A_i = i;
		}
		if (alphabet[i] == B) {
			B_i = i;
		}
	}
	return A_i < B_i;
}*/
bool isANotMoreThanB(person A, person B) {
	for (size_t i = 0; i < A.surname.length(); i++) {
		char A_char = A.surname[i];
		char B_char = (i < B.surname.length()) ? B.surname[i] : ' ';
		if (letterI(A.surname[i], i == 0) < letterI(B.surname[i], i == 0)) {
			return true;
		}
		else {
			if (A.surname[i] != B.surname[i]) {
				return false;
			}
		}
	}
	return true;
}

SCENARIO("Sort", "[s]") {
	//setlocale(LC_ALL, "ru_RU.utf8");
	std::ifstream ru("russian_letters.txt");
	for (size_t i = 0; i < 6; i++) {
		std::string str;
		ru >> str;
		russian_letters[i] = str[0];
	}
	ru.close();
	size_t n_persons = 2001;
	size_t RAM_amount = 10000;
	std::string names_file_name = "names.txt";
	std::string surnames_file_name = "surnames.txt";
	std::string database_file_name = "database.txt";
	std::string output_file_name = "sorted_database.txt";
	{
		Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons);
		Database_Sorter database_sorter(database_file_name, output_file_name, RAM_amount);
		size_t start = clock();
		//database_sorter.sortDatabase();
		size_t result = clock() - start;
		std::cout << result << std::endl;
		system("pause");
	}

	for (size_t i = 0; i < 0; i++) {
		size_t person1_i = rand() % n_persons;
		size_t person2_i = person1_i + rand() % (n_persons - person1_i);
		person person1 = readPerson(output_file_name, person1_i);
		person person2 = readPerson(output_file_name, person2_i);
		REQUIRE(isANotMoreThanB(person1, person2));
	}

	std::string str = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
	REQUIRE(letterI(str[1], true) == 2);
	REQUIRE(letterI(str[2], true) == 3);
	REQUIRE(letterI(str[3], true) == 4);
	REQUIRE(letterI(str[4], true) == 5);
}
<commit_msg>Update init.cpp<commit_after>#include "catch.hpp"
#include <iostream>
#include "Database_Creator.hpp"
#include "Database_Sorter.hpp"

person readPerson(std::string file_name, size_t index) {
	person result;
	std::ifstream file(file_name);
	for (size_t i = 0; i < index + 1; i++) {
		file >> result;
	}
	file.close();
	return result;
}
/*bool isALessThanB(char A, char B, bool is_capital) {
	std::string alphabet;
	if (is_capital) {
		alphabet = " АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
	}
	else {
		alphabet = " абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
	}
	size_t A_i;
	size_t B_i;
	for (size_t i = 0; i < alphabet.size(); i++) {
		if (alphabet[i] == A) {
			A_i = i;
		}
		if (alphabet[i] == B) {
			B_i = i;
		}
	}
	return A_i < B_i;
}*/
bool isANotMoreThanB(person A, person B) {
	for (size_t i = 0; i < A.surname.length(); i++) {
		char A_char = A.surname[i];
		char B_char = (i < B.surname.length()) ? B.surname[i] : ' ';
		if (letterI(A.surname[i], i == 0) < letterI(B.surname[i], i == 0)) {
			return true;
		}
		else {
			if (A.surname[i] != B.surname[i]) {
				return false;
			}
		}
	}
	return true;
}

SCENARIO("Sort", "[s]") {
	//setlocale(LC_ALL, "ru_RU.utf8");
	std::ifstream ru("russian_letters.txt");
	for (size_t i = 0; i < 6; i++) {
		std::string str;
		ru >> str;
		russian_letters[i] = str[0];
	}
	ru.close();
	size_t n_persons = 2001;
	size_t RAM_amount = 10000;
	std::string names_file_name = "names.txt";
	std::string surnames_file_name = "surnames.txt";
	std::string database_file_name = "database.txt";
	std::string output_file_name = "sorted_database.txt";
	{
		Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons);
		Database_Sorter database_sorter(database_file_name, output_file_name, RAM_amount);
		size_t start = clock();
		database_sorter.sortDatabase();
		size_t result = clock() - start;
		std::cout << result << std::endl;
		system("pause");
	}

	for (size_t i = 0; i < 0; i++) {
		size_t person1_i = rand() % n_persons;
		size_t person2_i = person1_i + rand() % (n_persons - person1_i);
		person person1 = readPerson(output_file_name, person1_i);
		person person2 = readPerson(output_file_name, person2_i);
		REQUIRE(isANotMoreThanB(person1, person2));
	}

	/*std::string str = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
	REQUIRE(letterI(str[1], true) == 2);
	REQUIRE(letterI(str[2], true) == 3);
	REQUIRE(letterI(str[3], true) == 4);
	REQUIRE(letterI(str[4], true) == 5);*/
}
<|endoftext|>


<commit_before>#include <matrix.hpp>
#include <catch.hpp>

SCENARIO("matrix init without parametrs", "[init wp]") {
	Matrix matrix;
	REQUIRE(matrix.rows() == 4);
	REQUIRE(matrix.columns() == 4);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init with parametrs", "[init withp]") {
	Matrix matrix(2,2);
	REQUIRE(matrix.rows() == 2);
	REQUIRE(matrix.columns() == 2);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init copy", "[init copy]") {
	Matrix matrix(2,2);
	Matrix matrix1(matrix);
	REQUIRE(matrix1.rows() == matrix.rows());
	REQUIRE(matrix1.columns() == matrix.columns());

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j));
		}
	}
}

SCENARIO("matrix fill", "[fill]") {
	Matrix matrix(2,2);
	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();
	matrix.fill("test1.txt");
	REQUIRE(matrix.Element(0,0) == 1);
	REQUIRE(matrix.Element(0,1) == 2);
	REQUIRE(matrix.Element(1,0) == 3);
	REQUIRE(matrix.Element(1,1) == 4);
}

SCENARIO("matrix sum", "[sum]") {
	Matrix matrix(2,2);
	Matrix matrix1(2,2);
	Matrix sum(2,2);

	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();

	matrix.fill("test1.txt");
	matrix1.fill("test1.txt");
	//ofstream sumfile("sumfile.txt");
	//sumfile << "2 4 6 8";
	//sum.fill("sumfile.txt");
	//sumfile.close();
	REQUIRE(matrix.Element(0,0) + matrix1.Element(0,0) == 2);
	REQUIRE(matrix.Element(0,1) + matrix1.Element(0,1) == 4);
	REQUIRE(matrix.Element(1,0) + matrix1.Element(1,0) == 6);
	REQUIRE(matrix.Element(1,1) + matrix1.Element(1,1) == 8);

}

SCENARIO("matrix Proizv", "[Pro]") {
	Matrix matrix(2,2);
	Matrix matrix1(2,2);
	Matrix Pro(2,2);

	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();

	matrix.fill("test1.txt");
	matrix1.fill("test1.txt");
	//ofstream sumfile("sumfile.txt");
	//sumfile << "2 4 6 8";
	//sum.fill("sumfile.txt");
	//sumfile.close();
	REQUIRE(matrix.Element(0,0) * matrix1.Element(0,0) + matrix.Element(1,0) * matrix1.Element(0,1) == 7);
	REQUIRE(matrix.Element(0,1) * matrix1.Element(0,0) + matrix.Element(1,1) * matrix1.Element(0,1) == 10);
	REQUIRE(matrix.Element(0,0) * matrix1.Element(1,0) + matrix.Element(1,0) * matrix1.Element(1,1) == 15);
	REQUIRE(matrix.Element(0,1) * matrix1.Element(1,0) + matrix.Element(1,1) * matrix1.Element(1,1) == 22);

}

<commit_msg>Update init.cpp<commit_after>#include <matrix.hpp>
#include <catch.hpp>

SCENARIO("matrix init without parametrs", "[init wp]") {
	Matrix matrix;
	REQUIRE(matrix.rows() == 4);
	REQUIRE(matrix.columns() == 4);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init with parametrs", "[init withp]") {
	Matrix matrix(2,2);
	REQUIRE(matrix.rows() == 2);
	REQUIRE(matrix.columns() == 2);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init copy", "[init copy]") {
	Matrix matrix(2,2);
	Matrix matrix1(matrix);
	REQUIRE(matrix1.rows() == matrix.rows());
	REQUIRE(matrix1.columns() == matrix.columns());

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j));
		}
	}
}

SCENARIO("matrix fill", "[fill]") {
	Matrix matrix(2,2);
	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();
	matrix.fill("test1.txt");
	REQUIRE(matrix.Element(0,0) == 1);
	REQUIRE(matrix.Element(0,1) == 2);
	REQUIRE(matrix.Element(1,0) == 3);
	REQUIRE(matrix.Element(1,1) == 4);
}

SCENARIO("matrix sum", "[sum]") {
	Matrix matrix(2,2);
	Matrix matrix1(2,2);
	Matrix sum(2,2);

	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();

	matrix.fill("test1.txt");
	matrix1.fill("test1.txt");
	//ofstream sumfile("sumfile.txt");
	//sumfile << "2 4 6 8";
	//sum.fill("sumfile.txt");
	//sumfile.close();
	REQUIRE(matrix.Element(0,0) + matrix1.Element(0,0) == 2);
	REQUIRE(matrix.Element(0,1) + matrix1.Element(0,1) == 4);
	REQUIRE(matrix.Element(1,0) + matrix1.Element(1,0) == 6);
	REQUIRE(matrix.Element(1,1) + matrix1.Element(1,1) == 8);

}

SCENARIO("matrix Proizv", "[Pro]") {
	Matrix matrix(2,2);
	Matrix matrix1(2,2);
	Matrix Pro(2,2);

	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();

	matrix.fill("test1.txt");
	matrix1.fill("test1.txt");
	//ofstream sumfile("sumfile.txt");
	//sumfile << "2 4 6 8";
	//sum.fill("sumfile.txt");
	//sumfile.close();
	REQUIRE(matrix.Element(0,0) * matrix1.Element(0,0) + matrix.Element(1,0) * matrix1.Element(0,1) == 7);
	REQUIRE(matrix.Element(0,1) * matrix1.Element(0,0) + matrix.Element(1,1) * matrix1.Element(0,1) == 10);
	REQUIRE(matrix.Element(0,0) * matrix1.Element(1,0) + matrix.Element(1,0) * matrix1.Element(1,1) == 15);
	REQUIRE(matrix.Element(0,1) * matrix1.Element(1,0) + matrix.Element(1,1) * matrix1.Element(1,1) == 22);

}

SCENARIO("matrix compare" , "[Comp]") {
	Matrix matrix(2,2);
	Matrix matrix1(2,2);

	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();

	matrix.fill("test1.txt");
	matrix1.fill("test1.txt");

	for (int i = 0; i<matrix.rows; i++) {
		for (int j = 0; j<matrix.columns;j++) {
			REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j);
				}
			}

}

SCENARIO("matrix compare" , "[Comp]") {
	Matrix matrix(2,2);
	Matrix matrix1(2,2);

	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();

	matrix.fill("test1.txt");
	for (int i = 0; i<matrix.rows; i++) {
		for (int j = 0; j<matrix.columns;j++) {
			matrix1.Element(i,j) = matrix.Element(i,j);
				}
			}

	REQUIRE(matrix1.Element(0,0) == 1);
	REQUIRE(matrix1.Element(0,1) == 2);
	REQUIRE(matrix1.Element(1,0) == 3);
	REQUIRE(matrix1.Element(1,1) == 4);

}

<|endoftext|>


<commit_before>#include <BinaryTree.hpp>
#include <catch.hpp>

SCENARIO ("init", "[init]")
{
  BinaryTree<int> obj;
  REQUIRE(obj.root_() == nullptr);
}

SCENARIO ("output to cout", "<<")
{
  BinaryTree<int> tree;
  tree.insert_node(3);
  REQUIRE( std::cout << tree );
}

SCENARIO("find_node", "[find_node]")
  {
    BinaryTree<int> obj;
    obj.insert_node(4);
    obj.insert_node(2);
    REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
    REQUIRE(obj.find_node(2, obj.root_())->data == 2);
  }

SCENARIO("insert", "[insert]")
{
  BinaryTree<int> obj;
  obj.insert_node(3);
  REQUIRE(obj.find_node(3, obj.root_())->data == 3);
}

SCENARIO("removeElement", "[remEl]")
{
  BinaryTree<int> obj;
  obj.insert_node(1);
  obj.insert_node(2);
  obj.insert_node(3);
  obj.insert_node(4);
  obj.insert_node(5);
  tree.remove_element(4);
  REQUIRE(obj.find_node(4, obj.root_()) != nullptr);
}
<commit_msg>Update init.cpp<commit_after>#include <BinaryTree.hpp>
#include <catch.hpp>

SCENARIO ("init", "[init]")
{
  BinaryTree<int> obj;
  REQUIRE(obj.root_() == nullptr);
}

SCENARIO ("output to cout", "<<")
{
  BinaryTree<int> tree;
  tree.insert_node(3);
  REQUIRE( std::cout << tree );
}

SCENARIO("find_node", "[find_node]")
  {
    BinaryTree<int> obj;
    obj.insert_node(4);
    obj.insert_node(2);
    REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
    REQUIRE(obj.find_node(2, obj.root_())->data == 2);
  }

SCENARIO("insert", "[insert]")
{
  BinaryTree<int> obj;
  obj.insert_node(3);
  REQUIRE(obj.find_node(3, obj.root_())->data == 3);
}

SCENARIO("removeElement", "[remEl]")
{
  BinaryTree<int> obj;
  obj.insert_node(1);
  obj.insert_node(2);
  obj.insert_node(3);
  obj.insert_node(4);
  obj.insert_node(5);
  obj.remove_element(4);
  REQUIRE(obj.find_node(4, obj.root_()) != nullptr);
}
<|endoftext|>


<commit_before>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include "sphere.hpp"
#include "box.hpp"
#include "material.hpp"
#include "sdfloader.hpp"
#include <glm/glm.hpp>
#include <glm/gtx/intersect.hpp>
#include <fstream>

TEST_CASE("Sphere default construction", "[constructor]") {
        Sphere s{};
        glm::vec3 c{0.0, 0.0, 0.0};
        REQUIRE(s.getRadius() == 0.0);
        REQUIRE(s.getCenter() == c);
        /*
        REQUIRE(s.getColor().r == 0.0);
        REQUIRE(s.getColor().g == 0.0);
        REQUIRE(s.getColor().b == 0.0);
        */
        REQUIRE(s.getName() == "");
}

TEST_CASE("Sphere construction", "[constructor]") {
        glm::vec3 c{1.0, 1.0, 1.0};
        Sphere s{c, 5.0, "Sphere"};
        REQUIRE(s.getRadius() == 5.0);
        REQUIRE(s.getCenter() == c);
        /*
        REQUIRE(s.getColor().r == 1.0);
        REQUIRE(s.getColor().g == 1.0);
        REQUIRE(s.getColor().b == 1.0);
        */
        REQUIRE(s.getName() == "Sphere");
}

/*
TEST_CASE("Sphere move construction", "[constructor]") {
        Sphere s1{5.0};
        Sphere s2(std::move(s1));
        glm::vec3 c{0.0, 0.0, 0.0};
        REQUIRE(s2.getRadius() == 5.0);
        REQUIRE(s2.getCenter() == c);
        REQUIRE(s1.getRadius() == 0.0);
        REQUIRE(s1.getCenter() == c);
}
*/
TEST_CASE("Sphere area calculation", "[area]") {
        Sphere s{1.0};
        REQUIRE(s.area() == Approx(12.566370614359173));
}

TEST_CASE("Sphere volume calculation", "[volume]") {
        Sphere s{1.0};
        REQUIRE(s.volume() == Approx(4.188790204786391));
}

TEST_CASE("Box default construction", "[constructor]") {
        Box b{};
        glm::vec3 p{0.0, 0.0, 0.0};
        REQUIRE(b.getMin() == p);
        REQUIRE(b.getMax() == p);
        /*
        REQUIRE(b.getColor().r == 0.0);
        REQUIRE(b.getColor().g == 0.0);
        REQUIRE(b.getColor().b == 0.0);
        */
        REQUIRE(b.getName() == "");
}

TEST_CASE("Box construction", "[constructor]") {
        glm::vec3 min{1.0, 1.0, 1.0};
        glm::vec3 max{5.0, 5.0, 5.0};
        Box b{min, max, "Box"};
        REQUIRE(b.getMin() == min);
        REQUIRE(b.getMax() == max);
        /*
        REQUIRE(b.getColor().r == 1.0);
        REQUIRE(b.getColor().g == 1.0);
        REQUIRE(b.getColor().b == 1.0);
        */
        REQUIRE(b.getName() == "Box");
}
/*
TEST_CASE("Box move construction", "[constructor]") {
        glm::vec3 min{1.0, 1.0, 1.0};
        glm::vec3 max{5.0, 5.0, 5.0};
        Box b1{min, max};
        Box b2(std::move(b1));
        REQUIRE(b2.getMin() == min);
        REQUIRE(b2.getMax() == max);
        glm::vec3 p{0.0, 0.0, 0.0};
        REQUIRE(b1.getMin() == p);
        REQUIRE(b1.getMax() == p);
}
*/
TEST_CASE("Box area calculation", "[area]") {
        glm::vec3 min{1.0, 1.0, 1.0};
        glm::vec3 max{5.0, 5.0, 5.0};
        Box b{min, max};
        REQUIRE(b.area() == Approx(96.0));
}

TEST_CASE("Box volume calculation", "[volume]") {
        glm::vec3 min{1.0, 1.0, 1.0};
        glm::vec3 max{5.0, 5.0, 5.0};
        Box b{min, max};
        REQUIRE(b.volume() == Approx(64.0));
}

TEST_CASE("Printing a Sphere", "[<<]") {
        Sphere s("Test");
        std::cout << s << std::endl;
}

TEST_CASE("Printing a Box", "[<<]") {
        Box b("Test");
        std::cout << b << std::endl;
}

TEST_CASE("intersectRaySphere", "[intersect]") {
        // Ray
        glm::vec3 ray_origin(0.0,0.0,0.0);
        // ray direction has to be normalized!
        // you can use:
        //      v = glm::normalize(some_vector)
        glm::vec3 ray_direction(0.0,0.0,1.0);

        // Sphere
        glm::vec3 sphere_center(0.0,0.0,5.0);
        float sphere_radius(1.0);

        float distance(0.0);
        auto result = glm::intersectRaySphere(
                ray_origin, ray_direction,
                sphere_center, sphere_radius,
                distance);
        REQUIRE(distance == Approx(4.0f));
}

TEST_CASE("intersect", "[intersect]") {
        Ray r{{0.0,0.0,0.0}, {0.0,0.0,1.0}};
        Sphere s{glm::vec3{0.0,0.0,5.0}, 1.0};

        float distance(0.0);

        REQUIRE(s.intersect(r, distance) == true);
        REQUIRE(distance == Approx(4.0f));
}
/*
TEST_CASE("shared_ptrs") {
    Color red(255, 0, 0);
    glm::vec3 position(0.0);

    std::cout << "-----------" << "\n";
    std::cout << "Aufgabe 6.7" << "\n";
    std::cout << "-----------" << std::endl;

    std::shared_ptr<Sphere> s1 =
        std::make_shared<Sphere>(position, 1.2, "sphere0", red);
    std::shared_ptr<Shape> s2 =
        std::make_shared<Sphere>(position, 1.2, "sphere1", red);

    s1->print(std::cout);
    s2->print(std::cout);
}

TEST_CASE("virtual destructor", "[virtual]") {
    Color red(255, 0, 0);
    glm::vec3 position(0.0);

    std::cout << "-----------" << "\n";
    std::cout << "Aufgabe 6.8" << "\n";
    std::cout << "-----------" << std::endl;

    Sphere* s1 = new Sphere(position, 1.2, "sphere0", red);
    Shape* s2 = new Sphere(position, 1.2, "sphere1", red);

    s1->print(std::cout);
    s2->print(std::cout);

    delete s1;
    delete s2;
}
*/
TEST_CASE("Material printing", "[<<]") {
        Material m{"Testmaterial", Color{1,0,0}, Color{0,1,0}, Color{0,0,1}, 15};
        std::cout << m << std::endl;
}

TEST_CASE("Loading an SDF file and printing it", "[loadSDF]") {
        auto vec = loadSDF("materials.sdf");
        for(auto it = vec.begin(); it != vec.end(); ++it) {
                std::cout << *it << std::endl;
        }
}

int main(int argc, char *argv[]) {
        return Catch::Session().run(argc, argv);
}<commit_msg>Add test for Box intersect.<commit_after>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include "sphere.hpp"
#include "box.hpp"
#include "material.hpp"
#include "sdfloader.hpp"
#include <glm/glm.hpp>
#include <glm/gtx/intersect.hpp>
#include <fstream>

TEST_CASE("Sphere default construction", "[constructor]") {
        Sphere s{};
        glm::vec3 c{0.0, 0.0, 0.0};
        REQUIRE(s.getRadius() == 0.0);
        REQUIRE(s.getCenter() == c);
        /*
        REQUIRE(s.getColor().r == 0.0);
        REQUIRE(s.getColor().g == 0.0);
        REQUIRE(s.getColor().b == 0.0);
        */
        REQUIRE(s.getName() == "");
}

TEST_CASE("Sphere construction", "[constructor]") {
        glm::vec3 c{1.0, 1.0, 1.0};
        Sphere s{c, 5.0, "Sphere"};
        REQUIRE(s.getRadius() == 5.0);
        REQUIRE(s.getCenter() == c);
        /*
        REQUIRE(s.getColor().r == 1.0);
        REQUIRE(s.getColor().g == 1.0);
        REQUIRE(s.getColor().b == 1.0);
        */
        REQUIRE(s.getName() == "Sphere");
}

/*
TEST_CASE("Sphere move construction", "[constructor]") {
        Sphere s1{5.0};
        Sphere s2(std::move(s1));
        glm::vec3 c{0.0, 0.0, 0.0};
        REQUIRE(s2.getRadius() == 5.0);
        REQUIRE(s2.getCenter() == c);
        REQUIRE(s1.getRadius() == 0.0);
        REQUIRE(s1.getCenter() == c);
}
*/
TEST_CASE("Sphere area calculation", "[area]") {
        Sphere s{1.0};
        REQUIRE(s.area() == Approx(12.566370614359173));
}

TEST_CASE("Sphere volume calculation", "[volume]") {
        Sphere s{1.0};
        REQUIRE(s.volume() == Approx(4.188790204786391));
}

TEST_CASE("Box default construction", "[constructor]") {
        Box b{};
        glm::vec3 p{0.0, 0.0, 0.0};
        REQUIRE(b.getMin() == p);
        REQUIRE(b.getMax() == p);
        /*
        REQUIRE(b.getColor().r == 0.0);
        REQUIRE(b.getColor().g == 0.0);
        REQUIRE(b.getColor().b == 0.0);
        */
        REQUIRE(b.getName() == "");
}

TEST_CASE("Box construction", "[constructor]") {
        glm::vec3 min{1.0, 1.0, 1.0};
        glm::vec3 max{5.0, 5.0, 5.0};
        Box b{min, max, "Box"};
        REQUIRE(b.getMin() == min);
        REQUIRE(b.getMax() == max);
        /*
        REQUIRE(b.getColor().r == 1.0);
        REQUIRE(b.getColor().g == 1.0);
        REQUIRE(b.getColor().b == 1.0);
        */
        REQUIRE(b.getName() == "Box");
}
/*
TEST_CASE("Box move construction", "[constructor]") {
        glm::vec3 min{1.0, 1.0, 1.0};
        glm::vec3 max{5.0, 5.0, 5.0};
        Box b1{min, max};
        Box b2(std::move(b1));
        REQUIRE(b2.getMin() == min);
        REQUIRE(b2.getMax() == max);
        glm::vec3 p{0.0, 0.0, 0.0};
        REQUIRE(b1.getMin() == p);
        REQUIRE(b1.getMax() == p);
}
*/
TEST_CASE("Box area calculation", "[area]") {
        glm::vec3 min{1.0, 1.0, 1.0};
        glm::vec3 max{5.0, 5.0, 5.0};
        Box b{min, max};
        REQUIRE(b.area() == Approx(96.0));
}

TEST_CASE("Box volume calculation", "[volume]") {
        glm::vec3 min{1.0, 1.0, 1.0};
        glm::vec3 max{5.0, 5.0, 5.0};
        Box b{min, max};
        REQUIRE(b.volume() == Approx(64.0));
}

TEST_CASE("Printing a Sphere", "[<<]") {
        Sphere s("Test");
        std::cout << s << std::endl;
}

TEST_CASE("Printing a Box", "[<<]") {
        Box b("Test");
        std::cout << b << std::endl;
}

TEST_CASE("intersectRaySphere", "[intersect]") {
        // Ray
        glm::vec3 ray_origin(0.0,0.0,0.0);
        // ray direction has to be normalized!
        // you can use:
        //      v = glm::normalize(some_vector)
        glm::vec3 ray_direction(0.0,0.0,1.0);

        // Sphere
        glm::vec3 sphere_center(0.0,0.0,5.0);
        float sphere_radius(1.0);

        float distance(0.0);
        auto result = glm::intersectRaySphere(
                ray_origin, ray_direction,
                sphere_center, sphere_radius,
                distance);
        REQUIRE(distance == Approx(4.0f));
}

TEST_CASE("intersect", "[intersect]") {
        Ray r{{0.0,0.0,0.0}, {0.0,0.0,1.0}};
        Sphere s{glm::vec3{0.0,0.0,5.0}, 1.0};

        float distance(0.0);

        REQUIRE(s.intersect(r, distance) == true);
        REQUIRE(distance == Approx(4.0f));
}
/*
TEST_CASE("shared_ptrs") {
    Color red(255, 0, 0);
    glm::vec3 position(0.0);

    std::cout << "-----------" << "\n";
    std::cout << "Aufgabe 6.7" << "\n";
    std::cout << "-----------" << std::endl;

    std::shared_ptr<Sphere> s1 =
        std::make_shared<Sphere>(position, 1.2, "sphere0", red);
    std::shared_ptr<Shape> s2 =
        std::make_shared<Sphere>(position, 1.2, "sphere1", red);

    s1->print(std::cout);
    s2->print(std::cout);
}

TEST_CASE("virtual destructor", "[virtual]") {
    Color red(255, 0, 0);
    glm::vec3 position(0.0);

    std::cout << "-----------" << "\n";
    std::cout << "Aufgabe 6.8" << "\n";
    std::cout << "-----------" << std::endl;

    Sphere* s1 = new Sphere(position, 1.2, "sphere0", red);
    Shape* s2 = new Sphere(position, 1.2, "sphere1", red);

    s1->print(std::cout);
    s2->print(std::cout);

    delete s1;
    delete s2;
}
*/
TEST_CASE("Material printing", "[<<]") {
        Material m{"Testmaterial", Color{1,0,0}, Color{0,1,0}, Color{0,0,1},
                    15};
        std::cout << m << std::endl;
}
/*
TEST_CASE("Loading an SDF file and printing it", "[loadSDF]") {
        auto vec = loadSDF("materials.sdf");
        for(auto it = vec.begin(); it != vec.end(); ++it) {
                std::cout << *it << std::endl;
        }
}
*/
TEST_CASE("intersectBox", "[intersect]") {
        Ray r{{0.0, 0.0, 0.0}, {1.0, 1.0, 1.0}};
        Box b{glm::vec3{0.0, 0.0, 0.0}, glm::vec3{1.0, 1.0, 1.0}};
        float t = 0;
        REQUIRE(b.intersect(r, t) == true);
}

int main(int argc, char *argv[]) {
        return Catch::Session().run(argc, argv);
}<|endoftext|>