<commit_before>#include <iostream>
#include <fstream>
#include <list>

#include <time.h>
#include <string.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>

#include "util.hpp"
#include "routingTable.hpp"
#include "fileTable.hpp"
#include "linuxTable.hpp"
#include "naive.hpp"
#include "basicTrie.hpp"
#include "pcTrie.hpp"
#include "manager.hpp"

using namespace std;

void print_usage(string name) {
	logInfo("Usage: " + name + "list-of-interfaces");
};

int main(int argc, char** argv){
	if(argc < 2){
		print_usage(argv[0]);
		return 0;
	}

	vector<string> interfaces;
	for(int i=1; i<argc; i++){
		interfaces.push_back(argv[i]);
	}

	Manager manager(interfaces);
	manager.run();
};

// old stuff, only here, because to good to delete
#if 0
#define CHALLENGE_VERSION 1

using namespace std;

struct challenge_header {
	uint32_t version;
	uint32_t num_entries;
	uint32_t reserved_1;
	uint32_t reserved_2;
};

struct challenge_entry {
	uint32_t addr;
	uint32_t next_hop;
};

void print_usage(string name){
	cout << "Usage: " << name << endl;
	cout << "\t --algo <name>\t\t\t\t valid: Naive, BasicTrie (default: BasicTrie)" << endl;
	cout << "\t --dump-fib\t\t\t\t pass rib filename to --fib-file" << endl;
	//cout << "\t --dump-challenge <challenge>" << endl;
	//cout << "\t --run-challenge <challenge>" << endl;
	//cout << "\t --convert-challenge <old> <new>" << endl;
	cout << "\t --fib-file <fib>\t\t\t default: kernel routing table" << endl;
};

#if 0
void dump_challenge(RoutingTable& table, string filename){
#define NUM_ENTRIES 10000000

	ofstream challenge_file (filename, ios::out | ios::binary);
	struct challenge_header header;
	header.version = CHALLENGE_VERSION;
	header.num_entries = NUM_ENTRIES;
	header.reserved_1 = 0;
	header.reserved_2 = 0;
	challenge_file.write((char*) &header, sizeof(challenge_header));

	BasicTrie lpm(table);

	for(int i=0; i<NUM_ENTRIES; i++){
		challenge_entry entry;
		entry.addr = random();
		entry.next_hop = (lpm.route(entry.addr)).next_hop;
		challenge_file.write((char*) &entry, sizeof(challenge_entry));
	}

	challenge_file.close();
};

template <typename LPM>
void run_challenge(RoutingTable& table, string challenge_filename){
	// read the challenge file
	int fd = open(challenge_filename.c_str(), 0);
	challenge_header header;
	int ret = read(fd, &header, sizeof(challenge_header));
	if(ret != sizeof(challenge_header)){
		cerr << "Error while reader challenge_header!" << endl;
		return;
	}
	if(header.version != CHALLENGE_VERSION){
		cerr << "challenge version is not supported!" << endl;
		return;
	}

	char* mmap_base =  (char*) mmap(
			NULL,
			header.num_entries * sizeof(challenge_entry) + sizeof(challenge_header),
			PROT_READ,
			MAP_PRIVATE | MAP_POPULATE,
			fd,
			0);

	if(mmap_base == MAP_FAILED){
		cerr << "mmap failed! errno: " << errno << endl;
		return;
	}

	challenge_entry* entries = (challenge_entry*) (mmap_base + sizeof(challenge_header));

	int failed = 0;
	int success = 0;

	LPM lpm(table);

	clock_t start = clock();
	for(unsigned int i=0; i<header.num_entries; i++){
		uint32_t res = (lpm.route(entries[i].addr)).next_hop;
		if(unlikely(res != entries[i].next_hop)){
			cout << "Failed IP: " << ip_to_str(entries[i].addr) << endl;
			cout << "Expected : " << ip_to_str(entries[i].next_hop) << endl;
			cout << "Got      : " << ip_to_str(res) << endl << endl;
			failed++;
		} else {
			success++;
		}
	}
	clock_t end = clock();

	float seconds = (1.0*(end-start)) / CLOCKS_PER_SEC;

	cerr << "Lookups took " << seconds << " seconds" << endl;
	cerr << "Rate: " << ((success + failed) / seconds) / 1000000 << " Mlps" << endl;

	cout << "Successful lookups: " << success << endl;
	cout << "Failed lookups: " << failed << endl;
};

void convert_challenge(string old_file, string new_file){
	// read the challenge file
	list<pair<uint32_t, uint32_t>> challenge;
	ifstream dump(old_file);
	regex regex("^(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)$");
	while(1) {
		bool finished = false;
		string line;
		if(dump.eof()){
			finished = true;
		} else {
			getline(dump, line);
		}
		if(dump.eof()){
			finished = true;
		}

		if(finished){
			break;
		}

		smatch m;
		uint32_t addr, next_hop;
		struct in_addr in_addr;

		regex_match(line, m, regex);

		inet_aton(m[1].str().c_str(), &in_addr);
		addr = ntohl(in_addr.s_addr);
		inet_aton(m[2].str().c_str(), &in_addr);
		next_hop = ntohl(in_addr.s_addr);

		challenge.push_back({addr, next_hop});
	}

	ofstream challenge_file (new_file, ios::out | ios::binary);
	struct challenge_header header;
	header.version = CHALLENGE_VERSION;
	header.num_entries = challenge.size();
	header.reserved_1 = 0;
	header.reserved_2 = 0;
	challenge_file.write((char*) &header, sizeof(challenge_header));

	for(auto& e : challenge){
		challenge_entry entry;
		entry.addr = e.first;
		entry.next_hop = e.second;
		challenge_file.write((char*) &entry, sizeof(challenge_entry));
	}

	challenge_file.close();

}
#endif

int main(int argc, char** argv){
	enum {INVALID_MODE, DUMP_FIB, DUMP_CHALLENGE, RUN_CHALLENGE, CONVERT_CHALLENGE} mode
		= INVALID_MODE;
	enum {INVALID_ALGO, NAIVE, BASICTRIE} algo = INVALID_ALGO;
	enum {FILETABLE, KERNEL} table_mode = KERNEL;

	if(argc < 2){
		print_usage(string(argv[0]));
		return 0;
	}

	int cmd_pos = 1;
	string filename;
	string challenge_filename = "";

	while(cmd_pos < argc){
		if(strcmp(argv[cmd_pos], "--algo") == 0){
			if(strcmp(argv[cmd_pos+1], "Naive") == 0)
				algo = NAIVE;
			else if (strcmp(argv[cmd_pos+1], "BasicTrie") == 0)
				algo = BASICTRIE;
#if 0
			else if (strcmp(argv[cmd_pos+1], "PCTrie") == 0)
				algo = PCTRIE;
#endif
			cmd_pos += 2;
		} else if(strcmp(argv[cmd_pos], "--dump-fib") == 0){
			mode = DUMP_FIB;
			cmd_pos += 1;
#if 0
		} else if(strcmp(argv[cmd_pos], "--dump-challenge") == 0){
			mode = DUMP_CHALLENGE;
			challenge_filename = string(argv[cmd_pos+1]);
			cmd_pos += 2;
		} else if(strcmp(argv[cmd_pos], "--run-challenge") == 0){
			mode = RUN_CHALLENGE;
			challenge_filename = string(argv[cmd_pos+1]);
			cmd_pos += 2;
		} else if(strcmp(argv[cmd_pos], "--convert-challenge") == 0){
			mode = CONVERT_CHALLENGE;
			filename = string(argv[cmd_pos+1]);
			challenge_filename = string(argv[cmd_pos+2]);
			cmd_pos += 3;
#endif
		} else if(strcmp(argv[cmd_pos], "--fib-file") == 0){
			table_mode = FILETABLE;
			filename = argv[cmd_pos+1];
			cmd_pos += 2;
		} else {
			print_usage(string(argv[0]));
			return 0;
		}
	}

	RoutingTable* table;
	switch(table_mode){
		case KERNEL:
			table = new LinuxTable();
		break;
		case FILETABLE:
			table = new FileTable(filename);
		break;
	}

	switch(mode){
		case DUMP_FIB:
			table->print_table();
		break;
#if 0
		case DUMP_CHALLENGE:
			dump_challenge(*table, challenge_filename);
		break;
		case RUN_CHALLENGE:
			switch(algo){
				case NAIVE:
					run_challenge<Naive>(*table, challenge_filename);
				break;
				case BASICTRIE:
					run_challenge<BasicTrie>(*table, challenge_filename);
				break;
#if 0
				case PCTRIE:
					run_challenge<PCTrie>(*table, challenge_filename);
				break;
#endif
				default:
					run_challenge<BasicTrie>(*table, challenge_filename);
				break;
			}
		break;
		case CONVERT_CHALLENGE:
			convert_challenge(filename, challenge_filename);
		break;
#endif
		default:
			print_usage(string(argv[0]));
		break;
	}

	return 0;
}
#endif
<commit_msg>fix usage function<commit_after>#include <iostream>
#include <fstream>
#include <list>

#include <time.h>
#include <string.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>

#include "util.hpp"
#include "routingTable.hpp"
#include "fileTable.hpp"
#include "linuxTable.hpp"
#include "naive.hpp"
#include "basicTrie.hpp"
#include "pcTrie.hpp"
#include "manager.hpp"

using namespace std;

void print_usage(string name) {
	logInfo("Usage: " + name + " <list-of-interfaces>");
};

int main(int argc, char** argv){
	if(argc < 2){
		print_usage(argv[0]);
		return 0;
	}

	vector<string> interfaces;
	for(int i=1; i<argc; i++){
		interfaces.push_back(argv[i]);
	}

	Manager manager(interfaces);
	manager.run();
};

// old stuff, only here, because to good to delete
#if 0
#define CHALLENGE_VERSION 1

using namespace std;

struct challenge_header {
	uint32_t version;
	uint32_t num_entries;
	uint32_t reserved_1;
	uint32_t reserved_2;
};

struct challenge_entry {
	uint32_t addr;
	uint32_t next_hop;
};

void print_usage(string name){
	cout << "Usage: " << name << endl;
	cout << "\t --algo <name>\t\t\t\t valid: Naive, BasicTrie (default: BasicTrie)" << endl;
	cout << "\t --dump-fib\t\t\t\t pass rib filename to --fib-file" << endl;
	//cout << "\t --dump-challenge <challenge>" << endl;
	//cout << "\t --run-challenge <challenge>" << endl;
	//cout << "\t --convert-challenge <old> <new>" << endl;
	cout << "\t --fib-file <fib>\t\t\t default: kernel routing table" << endl;
};

#if 0
void dump_challenge(RoutingTable& table, string filename){
#define NUM_ENTRIES 10000000

	ofstream challenge_file (filename, ios::out | ios::binary);
	struct challenge_header header;
	header.version = CHALLENGE_VERSION;
	header.num_entries = NUM_ENTRIES;
	header.reserved_1 = 0;
	header.reserved_2 = 0;
	challenge_file.write((char*) &header, sizeof(challenge_header));

	BasicTrie lpm(table);

	for(int i=0; i<NUM_ENTRIES; i++){
		challenge_entry entry;
		entry.addr = random();
		entry.next_hop = (lpm.route(entry.addr)).next_hop;
		challenge_file.write((char*) &entry, sizeof(challenge_entry));
	}

	challenge_file.close();
};

template <typename LPM>
void run_challenge(RoutingTable& table, string challenge_filename){
	// read the challenge file
	int fd = open(challenge_filename.c_str(), 0);
	challenge_header header;
	int ret = read(fd, &header, sizeof(challenge_header));
	if(ret != sizeof(challenge_header)){
		cerr << "Error while reader challenge_header!" << endl;
		return;
	}
	if(header.version != CHALLENGE_VERSION){
		cerr << "challenge version is not supported!" << endl;
		return;
	}

	char* mmap_base =  (char*) mmap(
			NULL,
			header.num_entries * sizeof(challenge_entry) + sizeof(challenge_header),
			PROT_READ,
			MAP_PRIVATE | MAP_POPULATE,
			fd,
			0);

	if(mmap_base == MAP_FAILED){
		cerr << "mmap failed! errno: " << errno << endl;
		return;
	}

	challenge_entry* entries = (challenge_entry*) (mmap_base + sizeof(challenge_header));

	int failed = 0;
	int success = 0;

	LPM lpm(table);

	clock_t start = clock();
	for(unsigned int i=0; i<header.num_entries; i++){
		uint32_t res = (lpm.route(entries[i].addr)).next_hop;
		if(unlikely(res != entries[i].next_hop)){
			cout << "Failed IP: " << ip_to_str(entries[i].addr) << endl;
			cout << "Expected : " << ip_to_str(entries[i].next_hop) << endl;
			cout << "Got      : " << ip_to_str(res) << endl << endl;
			failed++;
		} else {
			success++;
		}
	}
	clock_t end = clock();

	float seconds = (1.0*(end-start)) / CLOCKS_PER_SEC;

	cerr << "Lookups took " << seconds << " seconds" << endl;
	cerr << "Rate: " << ((success + failed) / seconds) / 1000000 << " Mlps" << endl;

	cout << "Successful lookups: " << success << endl;
	cout << "Failed lookups: " << failed << endl;
};

void convert_challenge(string old_file, string new_file){
	// read the challenge file
	list<pair<uint32_t, uint32_t>> challenge;
	ifstream dump(old_file);
	regex regex("^(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)$");
	while(1) {
		bool finished = false;
		string line;
		if(dump.eof()){
			finished = true;
		} else {
			getline(dump, line);
		}
		if(dump.eof()){
			finished = true;
		}

		if(finished){
			break;
		}

		smatch m;
		uint32_t addr, next_hop;
		struct in_addr in_addr;

		regex_match(line, m, regex);

		inet_aton(m[1].str().c_str(), &in_addr);
		addr = ntohl(in_addr.s_addr);
		inet_aton(m[2].str().c_str(), &in_addr);
		next_hop = ntohl(in_addr.s_addr);

		challenge.push_back({addr, next_hop});
	}

	ofstream challenge_file (new_file, ios::out | ios::binary);
	struct challenge_header header;
	header.version = CHALLENGE_VERSION;
	header.num_entries = challenge.size();
	header.reserved_1 = 0;
	header.reserved_2 = 0;
	challenge_file.write((char*) &header, sizeof(challenge_header));

	for(auto& e : challenge){
		challenge_entry entry;
		entry.addr = e.first;
		entry.next_hop = e.second;
		challenge_file.write((char*) &entry, sizeof(challenge_entry));
	}

	challenge_file.close();

}
#endif

int main(int argc, char** argv){
	enum {INVALID_MODE, DUMP_FIB, DUMP_CHALLENGE, RUN_CHALLENGE, CONVERT_CHALLENGE} mode
		= INVALID_MODE;
	enum {INVALID_ALGO, NAIVE, BASICTRIE} algo = INVALID_ALGO;
	enum {FILETABLE, KERNEL} table_mode = KERNEL;

	if(argc < 2){
		print_usage(string(argv[0]));
		return 0;
	}

	int cmd_pos = 1;
	string filename;
	string challenge_filename = "";

	while(cmd_pos < argc){
		if(strcmp(argv[cmd_pos], "--algo") == 0){
			if(strcmp(argv[cmd_pos+1], "Naive") == 0)
				algo = NAIVE;
			else if (strcmp(argv[cmd_pos+1], "BasicTrie") == 0)
				algo = BASICTRIE;
#if 0
			else if (strcmp(argv[cmd_pos+1], "PCTrie") == 0)
				algo = PCTRIE;
#endif
			cmd_pos += 2;
		} else if(strcmp(argv[cmd_pos], "--dump-fib") == 0){
			mode = DUMP_FIB;
			cmd_pos += 1;
#if 0
		} else if(strcmp(argv[cmd_pos], "--dump-challenge") == 0){
			mode = DUMP_CHALLENGE;
			challenge_filename = string(argv[cmd_pos+1]);
			cmd_pos += 2;
		} else if(strcmp(argv[cmd_pos], "--run-challenge") == 0){
			mode = RUN_CHALLENGE;
			challenge_filename = string(argv[cmd_pos+1]);
			cmd_pos += 2;
		} else if(strcmp(argv[cmd_pos], "--convert-challenge") == 0){
			mode = CONVERT_CHALLENGE;
			filename = string(argv[cmd_pos+1]);
			challenge_filename = string(argv[cmd_pos+2]);
			cmd_pos += 3;
#endif
		} else if(strcmp(argv[cmd_pos], "--fib-file") == 0){
			table_mode = FILETABLE;
			filename = argv[cmd_pos+1];
			cmd_pos += 2;
		} else {
			print_usage(string(argv[0]));
			return 0;
		}
	}

	RoutingTable* table;
	switch(table_mode){
		case KERNEL:
			table = new LinuxTable();
		break;
		case FILETABLE:
			table = new FileTable(filename);
		break;
	}

	switch(mode){
		case DUMP_FIB:
			table->print_table();
		break;
#if 0
		case DUMP_CHALLENGE:
			dump_challenge(*table, challenge_filename);
		break;
		case RUN_CHALLENGE:
			switch(algo){
				case NAIVE:
					run_challenge<Naive>(*table, challenge_filename);
				break;
				case BASICTRIE:
					run_challenge<BasicTrie>(*table, challenge_filename);
				break;
#if 0
				case PCTRIE:
					run_challenge<PCTrie>(*table, challenge_filename);
				break;
#endif
				default:
					run_challenge<BasicTrie>(*table, challenge_filename);
				break;
			}
		break;
		case CONVERT_CHALLENGE:
			convert_challenge(filename, challenge_filename);
		break;
#endif
		default:
			print_usage(string(argv[0]));
		break;
	}

	return 0;
}
#endif
<|endoftext|>


<commit_before>#include "filestream_parser/filestream_parser.h"

int main(int argc, const char* argv[])
{
    if(argc < 2)
    {
        std::cout << "USAGE: ti-flashstream-flasher [I2C Device] [Slave Address] [file]" << std::endl;
        return -1;
    }

    std::string i2cDevice = argv[1];
    int slaveAddress = std::stoi(argv[2]);
    std::string flashStreamFile = argv[3];

    std::cout << "opening i2c device: " << i2cDevice << " with slave address: " << slaveAddress << std::endl;

    //I2CInterface i2cInterface(i2cDevice, slaveAddress);
    FilestreamParser parser(flashStreamFile);

    parser.flash();

    return 0;
}

<commit_msg>Removed commented file<commit_after>#include "filestream_parser/filestream_parser.h"

int main(int argc, const char* argv[])
{
    if(argc < 2)
    {
        std::cout << "USAGE: ti-flashstream-flasher [I2C Device] [Slave Address] [file]" << std::endl;
        return -1;
    }

    std::string i2cDevice = argv[1];
    int slaveAddress = std::stoi(argv[2]);
    std::string flashStreamFile = argv[3];

    std::cout << "opening i2c device: " << i2cDevice << " with slave address: " << slaveAddress << std::endl;

    I2CInterface i2cInterface(i2cDevice, slaveAddress);
    FilestreamParser parser(flashStreamFile);

    parser.flash();

    return 0;
}

<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <time.h>
#include <Windows.h>
#include <math.h>
#include <map>
#include <vector>
#include <iostream>
#include "ICJs_compute.h"
#include "ICJs_types.h"
#include "ICJs_util.h"
#include "ICJs_parser.h"
#include <sstream>

#define FORGREEN (FOREGROUND_GREEN | FOREGROUND_INTENSITY)
#define FORBLACK (FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED)
#define FORRED   (FOREGROUND_RED | FOREGROUND_INTENSITY)

using namespace std;

void printHeader(void);
void printCredits(void);
string readIn(int i);
string writeOut(string in);
void print(vector<Element> out);

HANDLE outputHandler = GetStdHandle(STD_OUTPUT_HANDLE);

int main(int argc, char **argv)
{

	printHeader();
	string input = "In ", output = "Out";
	string rawInput = "";
	string result = "nil";
	map<string, Element> variables;
	Element ret;
	vector<Element> rets;
	vector<Element> output_;
	vector<string> statements;

	int i = 0;
	while (true)
	{
		output_.clear();
		i++;
		SetConsoleTextAttribute(outputHandler, FORGREEN);
		cout << input << "[" << i << "]: ";
		SetConsoleTextAttribute(outputHandler, FORBLACK);
		rawInput = readIn(int(log10(i)));
		if (rawInput.find("exit") != string::npos)
		{
			break;
		}
		if (rawInput == "credits")
		{
			printCredits();
			continue;
		}
		Util::split(rawInput, "\n", &statements, false);

		int error = Parser::parse(statements, variables, output_);

		//result = writeOut(Util::trim(output_));

		SetConsoleTextAttribute(outputHandler, FORRED);
		cout << output << "[" << i << "]: ";
		SetConsoleTextAttribute(outputHandler, FORBLACK);
		print(output_);

		if (error != Global::_ok)
			cout << "Error!" << endl;
		statements.clear();
		cout << endl;
		cout << endl;
	}
	return 0;
}

void printHeader(void)
{
	time_t now;
	time(&now);
	struct tm tmTmp;
	char stTmp[100];
	localtime_s(&tmTmp, &now);
	asctime_s(stTmp, &tmTmp);
	cout << "Interpretive C++ for JavaScript Console 1.0" << endl;
	cout << "ICJ 1.0 | " << stTmp;
	cout << "Type \"credits\" for mor information" << endl << endl;
	cout << "ICJ -- A lightweight tnterpreter for JavaScript powered by C++" << endl;
	cout << "ICJ is brought to you by Welly Zhang, Tianji Zheng, Qinbin Tan and Qiankun Zhang." << endl << endl;
	return;
}

void printCredits(void)
{
	cout << "We are grateful for users of CNBlog, CPlusPlus website developers, Googlers who share publicly their ideas about C++ ";
	cout << "and anybody who has ever lent a helping hand when we are developing this interactive interpreter, without whom the ";
	cout << "project might take way longer to finish than expected." << endl;
	cout << endl;
	return;
}

string readIn(int i)
{
	string stmt = "";
	char c;
	bool flagSlash = 0;
	while (true)
	{
		c = getchar();
		if (c == '\n' && flagSlash)
		{
			SetConsoleTextAttribute(outputHandler, FORGREEN);
			cout << " ";
			for (int j = 0; j < i + 1; j++)
			{
				cout << " ";
			}

			cout << " " << "...: ";
			SetConsoleTextAttribute(outputHandler, FORBLACK);
			flagSlash = 0;
		}
		else if (c == '\n' && !flagSlash)
		{
			break;
		}
		else if (c == '\\')
		{
			flagSlash = 1;
			stmt += '\n';
		}
		else
		{
			stmt += c;
		}
	}
	return stmt;
}

string writeOut(string in)
{
	vector<string> stmts;
	string out;
	Util::split(in, "\n", &stmts, false);
	out = in;
	return out;
}

void print(vector<Element> rets)
{
	for (int i = 0; i < rets.size(); i++)
	{
		switch (rets[i].type)
		{
		case Global::_number:
			cout << *(double *)(rets[i].data);
			if (i != rets.size() - 1)
				cout << ", ";
			break;
		case Global::_boolean:
			cout << *(bool *)(rets[i].data);
			if (i != rets.size() - 1)
				cout << ", ";
			break;
		case Global::_string:
			cout << "\"" <<*(string *)(rets[i].data) << "\"";
			if (i != rets.size() - 1)
				cout << ", ";
			break;
		case Global::_array:
			cout << "[";
			print(*(vector<Element> *)rets[i].data);
			cout << "]";
			if (i != rets.size() - 1)
				cout << ", ";
			break;
		}
	}
}<commit_msg>file run<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <time.h>
#include <Windows.h>
#include <math.h>
#include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include "ICJs_compute.h"
#include "ICJs_types.h"
#include "ICJs_util.h"
#include "ICJs_parser.h"

#define FORGREEN (FOREGROUND_GREEN | FOREGROUND_INTENSITY)
#define FORBLACK (FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED)
#define FORRED   (FOREGROUND_RED | FOREGROUND_INTENSITY)

using namespace std;

void printHeader(void);
void printCredits(void);
string readIn(int i);
string writeOut(string in);
void print(vector<Element> out);

HANDLE outputHandler = GetStdHandle(STD_OUTPUT_HANDLE);

int main(int argc, char **argv)
{

	printHeader();
	char buf[256];
	string input = "In ", output = "Out";
	string rawInput = "";
	string result = "nil";
	map<string, Element> variables;
	Element ret;
	vector<Element> rets;
	vector<Element> output_;
	vector<string> statements;

	int i = 0;
	while (true)
	{
		output_.clear();
		i++;
		SetConsoleTextAttribute(outputHandler, FORGREEN);
		cout << input << "[" << i << "]: ";
		SetConsoleTextAttribute(outputHandler, FORBLACK);
		rawInput = readIn(int(log10(i)));

		if (rawInput.find("exit") != string::npos)
		{
			break;
		}
		else if (rawInput == "credits")
		{
			printCredits();
			continue;
		}
		Util::split(rawInput, "\n", &statements, false);
		if (rawInput.find("%load") != string::npos){
			statements.clear();
			string oper, filename;
			istringstream is(rawInput);
			is >> oper >> filename;
			ifstream file;
			file.open(filename);
			while (file.getline(buf, 256)){
				statements.push_back(string(buf));
			}
			file.close();
		}

		int error = Parser::parse(statements, variables, output_);

		//result = writeOut(Util::trim(output_));

		SetConsoleTextAttribute(outputHandler, FORRED);
		cout << output << "[" << i << "]: ";
		SetConsoleTextAttribute(outputHandler, FORBLACK);
		print(output_);

		if (error != Global::_ok)
			cout << "Error!" << endl;
		statements.clear();
		cout << endl;
		cout << endl;
	}
	return 0;
}

void printHeader(void)
{
	time_t now;
	time(&now);
	struct tm tmTmp;
	char stTmp[100];
	localtime_s(&tmTmp, &now);
	asctime_s(stTmp, &tmTmp);
	cout << "Interpretive C++ for JavaScript Console 1.0" << endl;
	cout << "ICJ 1.0 | " << stTmp;
	cout << "Type \"credits\" for mor information" << endl << endl;
	cout << "ICJ -- A lightweight tnterpreter for JavaScript powered by C++" << endl;
	cout << "ICJ is brought to you by Welly Zhang, Tianji Zheng, Qinbin Tan and Qiankun Zhang." << endl << endl;
	return;
}

void printCredits(void)
{
	cout << "We are grateful for users of CNBlog, CPlusPlus website developers, Googlers who share publicly their ideas about C++ ";
	cout << "and anybody who has ever lent a helping hand when we are developing this interactive interpreter, without whom the ";
	cout << "project might take way longer to finish than expected." << endl;
	cout << endl;
	return;
}

string readIn(int i)
{
	string stmt = "";
	char c;
	bool flagSlash = 0;
	while (true)
	{
		c = getchar();
		if (c == '\n' && flagSlash)
		{
			SetConsoleTextAttribute(outputHandler, FORGREEN);
			cout << " ";
			for (int j = 0; j < i + 1; j++)
			{
				cout << " ";
			}

			cout << " " << "...: ";
			SetConsoleTextAttribute(outputHandler, FORBLACK);
			flagSlash = 0;
		}
		else if (c == '\n' && !flagSlash)
		{
			break;
		}
		else if (c == '\\')
		{
			flagSlash = 1;
			stmt += '\n';
		}
		else
		{
			stmt += c;
		}
	}
	return stmt;
}

string writeOut(string in)
{
	vector<string> stmts;
	string out;
	Util::split(in, "\n", &stmts, false);
	out = in;
	return out;
}

void print(vector<Element> rets)
{
	for (int i = 0; i < rets.size(); i++)
	{
		switch (rets[i].type)
		{
		case Global::_number:
			cout << *(double *)(rets[i].data);
			if (i != rets.size() - 1)
				cout << ", ";
			break;
		case Global::_boolean:
			cout << *(bool *)(rets[i].data);
			if (i != rets.size() - 1)
				cout << ", ";
			break;
		case Global::_string:
			cout << "\"" <<*(string *)(rets[i].data) << "\"";
			if (i != rets.size() - 1)
				cout << ", ";
			break;
		case Global::_array:
			cout << "[";
			print(*(vector<Element> *)rets[i].data);
			cout << "]";
			if (i != rets.size() - 1)
				cout << ", ";
			break;
		}
	}
}<|endoftext|>


<commit_before>#include "common.hpp"
#include "compiler.hpp"
#include "runtime.hpp"
#include "parser/parser.hpp"
#include "classes/exception.hpp"
#include "classes/string.hpp"
#include "classes/array.hpp"
#include "classes/fixnum.hpp"
#include "modules/kernel.hpp"
#include "platform/platform.hpp"
#include "block.hpp"
#include "document.hpp"

#ifdef MIRB_DEBUG_COMPILER
	#include "tree/printer.hpp"
#endif

using namespace Mirb;

void report_exception()
{
	Exception *exception = context->exception;

	swallow_exception();

	OnStack<1> os(exception);

	if(trap_exception([&] {
		Platform::color<Platform::Red>(inspect(class_of(exception)));

		if(exception->message)
			Platform::color<Platform::Bold>(": " + exception->message->string.get_string() );

		std::cerr << "\n";

		StackFrame::print_backtrace(exception->backtrace);
	}))
	{
		std::cerr << "Unable to inspect exception";
	}

	std::cerr << "\n";
}

int main(int argc, const char *argv[])
{
	Mirb::initialize(true);

	if(argc > 1)
	{
		int index = 1;

		if(strcmp(argv[index], "-v") == 0)
		{
			std::cout << "mirb 0.1" << std::endl;
			index++;
		}

		if(strcmp(argv[index], "--syntax") == 0)
		{
			int result = 0;

			for(int i = ++index; i < argc; ++i)
			{
				MemoryPool::Base memory_pool;
				CharArray filename = (const char_t *)argv[i];

				char_t *data;
				size_t length;
				bool loaded;
				CharArray full_path;

				if(trap_exception([&] { Kernel::read_file(filename, true, false, full_path, loaded, data, length); }))
				{
					report_exception();
					return 1;
				}

				Document *document = Collector::allocate_pinned<Document>();

				document->data = (const char_t *)data;
				document->length = length;
				document->name = full_path;

				Parser parser(symbol_pool, memory_pool, document);

				parser.load();
				parser.parse_main();

				if(!parser.messages.empty())
					result = 1;

				for(auto i = parser.messages.begin(); i != parser.messages.end(); ++i)
					i().print();
			}

			return result;
		}

		CharArray exec = CharArray((const char_t *)argv[index++]);

		Array *new_argv = Collector::allocate<Array>();

		for(int i = index; i < argc; ++i)
		{
			new_argv->vector.push(CharArray((const char_t *)argv[i]).to_string());
		}

		set_const(context->object_class, Symbol::get("ARGV"), new_argv);

		if(!Kernel::load(exec.to_string()))
		{
			report_exception();
			return 1;
		}

		return 0;
	}

	while(1)
	{
		mirb_debug(Collector::collect());

		std::string line;

		std::getline(std::cin, line);

		Block *block;

		{
			MemoryPool::Base memory_pool;
			Document *document = Collector::allocate_pinned<Document>();

			document->copy((const char_t *)line.c_str(), line.length());

			document->name = "Input";

			Parser parser(symbol_pool, memory_pool, document);

			parser.load();

			if(parser.lexeme() == Lexeme::END && parser.messages.empty())
				break;

			Tree::Scope *scope = parser.parse_main();

			if(!parser.messages.empty())
			{
				for(auto i = parser.messages.begin(); i != parser.messages.end(); ++i)
					i().print();

				continue;
			}

			#ifdef MIRB_DEBUG_COMPILER
				DebugPrinter printer;

				std::cout << "Parsing done.\n-----\n";
				std::cout << printer.print_node(scope->group);
				std::cout << "\n-----\n";
			#endif

			block = Compiler::compile(scope, memory_pool);
		}

		value_t result = call_code(block, context->main, Symbol::get("main"), context->object_scope, value_nil, 0, 0);

		if(result)
			std::cout << "=> " << inspect_object(result) << "\n";
		else
			report_exception();
	}

	std::cout << std::endl << "Number of collections: " << Collector::collections << std::endl;
	std::cout << "Memory allocated: " << (Collector::memory / 1024) <<  " KiB" << std::endl;
	std::cout << "Regions allocated: " << Collector::region_count << std::endl;
	std::cout << "Regions freed: " << Collector::region_free_count << std::endl;
	std::cout << "Exiting gracefully..." << std::endl;

	Mirb::finalize();

	return 0;
}
<commit_msg>Fixed a bug.<commit_after>#include "common.hpp"
#include "compiler.hpp"
#include "runtime.hpp"
#include "parser/parser.hpp"
#include "classes/exception.hpp"
#include "classes/string.hpp"
#include "classes/array.hpp"
#include "classes/fixnum.hpp"
#include "modules/kernel.hpp"
#include "platform/platform.hpp"
#include "block.hpp"
#include "document.hpp"

#ifdef MIRB_DEBUG_COMPILER
	#include "tree/printer.hpp"
#endif

using namespace Mirb;

void report_exception()
{
	Exception *exception = context->exception;

	swallow_exception();

	OnStack<1> os(exception);

	if(trap_exception([&] {
		Platform::color<Platform::Red>(inspect(class_of(exception)));

		if(exception->message)
			Platform::color<Platform::Bold>(": " + exception->message->string.get_string() );

		std::cerr << "\n";

		StackFrame::print_backtrace(exception->backtrace);
	}))
	{
		std::cerr << "Unable to inspect exception";
	}

	std::cerr << "\n";
}

int main(int argc, const char *argv[])
{
	Mirb::initialize(true);

	if(argc > 1)
	{
		int index = 1;

		if(strcmp(argv[index], "-v") == 0)
		{
			std::cout << "mirb 0.1" << std::endl;
			index++;
		}

		if(strcmp(argv[index], "--syntax") == 0)
		{
			int result = 0;

			for(int i = ++index; i < argc; ++i)
			{
				MemoryPool::Base memory_pool;
				CharArray filename = (const char_t *)argv[i];

				char_t *data;
				size_t length;
				bool loaded;
				CharArray full_path;

				if(trap_exception([&] { Kernel::read_file(filename, true, false, full_path, loaded, data, length); }))
				{
					report_exception();
					return 1;
				}

				Document *document = Collector::allocate_pinned<Document>();

				document->data = (const char_t *)data;
				document->length = length;
				document->name = full_path;

				Parser parser(symbol_pool, memory_pool, document);

				parser.load();
				parser.parse_main();

				if(!parser.messages.empty())
					result = 1;

				for(auto i = parser.messages.begin(); i != parser.messages.end(); ++i)
					i().print();
			}

			return result;
		}

		CharArray exec = CharArray((const char_t *)argv[index++]);

		Array *new_argv = Collector::allocate<Array>();

		for(int i = index; i < argc; ++i)
		{
			new_argv->vector.push(CharArray((const char_t *)argv[i]).to_string());
		}

		set_const(context->object_class, Symbol::get("ARGV"), new_argv);

		if(trap_exception([&] { Kernel::load(exec.to_string()); }))
		{
			report_exception();
			return 1;
		}

		return 0;
	}

	while(1)
	{
		mirb_debug(Collector::collect());

		std::string line;

		std::getline(std::cin, line);

		Block *block;

		{
			MemoryPool::Base memory_pool;
			Document *document = Collector::allocate_pinned<Document>();

			document->copy((const char_t *)line.c_str(), line.length());

			document->name = "Input";

			Parser parser(symbol_pool, memory_pool, document);

			parser.load();

			if(parser.lexeme() == Lexeme::END && parser.messages.empty())
				break;

			Tree::Scope *scope = parser.parse_main();

			if(!parser.messages.empty())
			{
				for(auto i = parser.messages.begin(); i != parser.messages.end(); ++i)
					i().print();

				continue;
			}

			#ifdef MIRB_DEBUG_COMPILER
				DebugPrinter printer;

				std::cout << "Parsing done.\n-----\n";
				std::cout << printer.print_node(scope->group);
				std::cout << "\n-----\n";
			#endif

			block = Compiler::compile(scope, memory_pool);
		}

		value_t result = call_code(block, context->main, Symbol::get("main"), context->object_scope, value_nil, 0, 0);

		if(result)
			std::cout << "=> " << inspect_object(result) << "\n";
		else
			report_exception();
	}

	std::cout << std::endl << "Number of collections: " << Collector::collections << std::endl;
	std::cout << "Memory allocated: " << (Collector::memory / 1024) <<  " KiB" << std::endl;
	std::cout << "Regions allocated: " << Collector::region_count << std::endl;
	std::cout << "Regions freed: " << Collector::region_free_count << std::endl;
	std::cout << "Exiting gracefully..." << std::endl;

	Mirb::finalize();

	return 0;
}
<|endoftext|>


<commit_before>//#include "util.hpp"
#include "control.hpp"
#include "main.hpp"
#include "system.hpp"
#include "model.hpp"
#include "view.hpp"

//#include <chrono>
#include <iostream>
//#include <thread>

#include "omp.h"
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

using namespace System;
using PB = Printer_Base;

int main(int argc, const char **argv) {
	std::atomic_bool alive(true);
	Control::control ctl;
	ctl.run(alive, "share/shade.vert",
			"share/shade.frag");
	return 0;
}
<commit_msg>Removed unnecessary inclusions<commit_after>#include "control.hpp"
#include "main.hpp"
#include "system.hpp"
#include "model.hpp"
#include "view.hpp"

#include <iostream>

#include "omp.h"
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

using namespace System;
using PB = Printer_Base;

int main(int argc, const char **argv) {
	std::atomic_bool alive(true);
	Control::control ctl;
	ctl.run(alive, "share/shade.vert",
			"share/shade.frag");
	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <string.h>
#include <typeinfo>
#include <boost/tokenizer.hpp>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
#include <stack>

using namespace std;
using namespace boost;

int execute(char** args, bool &prev, bool &prev_prev, int con, int prev_con){
   //pass in the command and previous
    if((prev == false) && (con != 2) && (prev_con != 2)){                //check if the last one was false
        return EXIT_FAILURE;              //will/should only work for &&
    }
    if((prev == true) && (prev_con == 2)){
      return 0;//EXIT_FAILURE;
    }
        if (strcmp(args[0], "exit") == 0){    //if exit is the command
        exit(0);                          //then exit
    }
    pid_t pid = fork();                   //start forking
        if (pid == -1){                       //fail to fork error
            perror("failed to fork");
            return EXIT_FAILURE;
    }
    else if(pid == 0){                     //start the process
        if(execvp(args[0], args) == -1){   //checks to see if it failed
            perror("execvp");              //if so output error and exit
	          exit(1);
	          return EXIT_FAILURE;
        }
    }
    int status;
    if ( waitpid(pid, &status, 0) == -1 ) { //waitpid waits(not sure what it does)
        perror("waitpid failed");
        exit(1);
        return EXIT_FAILURE;
    }
    if(WIFEXITED(status)){               //always goes into here(I think so)
        const int es = WEXITSTATUS(status);  // checks what the exit was
        //cout << "ES " << es << endl;
	      if(es != 0){                               //if exit was 1 then it failed(IMPORTANT)
		        return EXIT_FAILURE;
        }
    }
return EXIT_SUCCESS;                         //else return 0 for true
}

void Parse(vector<string> &ParseString, int size, bool P_previous, bool P_previous_prev, int P_conn, int P_conn_prev){
if(size < 1){                                       //passing in nothing = return
    return;
}

if(ParseString.at(0).at(0) == '('){
cout << "paranthesis: " << endl;
}

int ParseSize;                                      // will need variables for later
string connector;                                   //will hold the ;/&&/||
int P_con_prev = P_conn;
int P_con;
unsigned i = 0;                                     //basic counter
vector<string> S_T_E;                               //empty vector to be filled in

while((i < ParseString.size())
    && (ParseString.at(i) != ";")                   //creates the string
    && (ParseString.at(i) != "||")                  //that will execute
    && (ParseString.at(i) != "&&")){                //stops when connector/empty
        S_T_E.push_back(ParseString.at(i));
        ++i;
        ParseSize = i;
    }

string SP = ParseString.at(0);                       //if input is ;/&&/|| then error
    if((SP == ";") || (SP == "||") || (SP == "&&")){
        ParseString.erase(ParseString.begin(), ParseString.end());  //delete full string
        cout << "bash: syntax error near unexpected token '" <<  SP << "'" << endl;
        return;
    }

        if(i == ((ParseString.size()))){            //checks the last character
           connector = "0";
           P_con = 0;                        // 0 connector
           //cout << " in 0" << endl;
        }                                           //sets connnector
        else if(ParseString.at(i) == "&&"){         //&& connector
              connector = "&&";
              P_con = 1;
              //cout << " in &&" << endl;
        }
        else if(ParseString.at(i) == "||"){         //|| connector
              connector = "||";
              P_con = 2;
              //cout << " in ||" << endl;
        }
        else if(ParseString.at(i) == ";"){          // ; connector
              connector = ";";
              P_con = 3;
              //cout << " in ;" << endl;
        }

char** args = new char*[128];                        //creates new array to store the characters
    for(int i = 0; i < ParseSize; i++){
        char * temp = strdup(S_T_E.at(i).c_str());
        args[i] = temp;
    }

    if(ParseSize > 126){                             // limit of 127 strings as one command
        cout << "INPUT TOO LARGE" << endl;
        return;
    }
    args[ParseSize] = '\0';                          // null terminating character at the end

    int temp = execute(args, P_previous, P_previous_prev, P_con, P_con_prev);              //checks whether it executed or not
    P_previous_prev = P_previous;

    if(temp == 0){                                  // sets out boolean P_previous
        P_previous = true;
    }
    else{
        P_previous = false;
    }

        if(connector == "0"){                   //should be empty but parse will handle it
            ParseString.erase(ParseString.begin(), ParseString.begin() + i);

            P_previous = true;
            Parse(ParseString, ParseString.size(), P_previous, P_previous_prev, P_con, P_con_prev);
        }
        if(connector == "&&"){                   //&& case(only one not set to true*******)
            ParseString.erase(ParseString.begin(), ParseString.begin() + i + 1);

            Parse(ParseString, ParseString.size(), P_previous, P_previous_prev, P_con, P_con_prev);
        }
        if(connector == "||"){                   //|| case
            ParseString.erase(ParseString.begin(), ParseString.begin() + i + 1);

            if((P_previous_prev == true) && (P_con_prev == 2)){
            P_previous = true;
            }
            Parse(ParseString, ParseString.size(), P_previous, P_previous_prev, P_con, P_con_prev);
        }
        if(connector == ";"){                    //; case
            ParseString.erase(ParseString.begin(), ParseString.begin() + i + 1);

            P_previous = true;
            Parse(ParseString, ParseString.size(),  P_previous, P_previous_prev, P_con, P_con_prev);
        }
        return;
}
//////////////////////IGNORE THIS CODE, JUST DELETES THE COMMENT AND PRINTS////////////////////////////////////
void string_check(string &s, bool &Is_Comment){//helper function for the comment delete
        for(unsigned i = 0; i < s.size(); ++i){
            char temp = s.at(i);               //takes in a string
            if(temp == '#'){                   //compares it to the #
                Is_Comment = false;            //if true then set flag/boolean
            }
        }
}
void Delete_Comment(vector<string> &CC){       //takes in our full vector
        vector<string>::iterator it;           //iterates through the vector
        bool Comment_Checker = true;
        int i = 0;
       	for(it = CC.begin(); it != CC.end(); ++it){
       	    string test = "";
            test = *it;
            ++i;
            string str(test);                   //passes each individual string
            string_check(test, Comment_Checker);//to our helper function
            if(Comment_Checker == false){       //deletes everything past the #
                CC.erase(CC.begin() + i - 1, CC.end());
                return;
            }
       	}
}
void Print(vector<string> pts){                  //function that prints string vector
	vector<string>::iterator it;                   //helped when doing the first steps
	    for(it = pts.begin(); it != pts.end(); ++it){
      cout << *it << " ";                      //not really needed(the print function)
      }
}

bool Prec_checker(vector<string> prec){
stack<char>  S;
	for(int j = 0; j < prec.size(); ++j){
    for(int i = 0; i < prec.at(j).size(); ++i){
		if(prec.at(j).at(i) == '(')
			S.push(prec.at(j).at(i));

		else if(prec.at(j).at(i) == ')'){
			if(S.empty())
				return false;
			else
				S.pop();
		}
   }
	}
	return S.empty() ? true:false;
}

//////////////////////IGNORE THIS CODE, JUST DELETES THE COMMENT AND PRINTS////////////////////////////////////

int main(){

bool MainPrevious = true;   //allows us to run our first command
bool MainPrevious_prev = false;
vector<string> cmd;         //vector to hold our string
string str;                 //will simply be our input string

while(1){
    cout << "$ ";                                           //outputs the $ every iteration

    cmd.erase(cmd.begin(), cmd.end());
    getline(cin, str);                                      //gets input from user
    char_separator<char> delim(" ", ";" "#");               // parameters for our input
    tokenizer< char_separator<char> > mytok(str, delim);

    for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); ++it){
    cmd.push_back(*it);                                     //push to our cmd vector
    }

    Delete_Comment(cmd);                                     // checks for #
    bool done = Prec_checker(cmd);                                       //makes sure even number of precedence
    if(done == false){
    cout << "unmatched paranthesis: " << endl;
    cmd.erase(cmd.begin(), cmd.end());
    }
    int size = cmd.size();                                   //gets updated size(if changed)
    Parse(cmd, size, MainPrevious, MainPrevious_prev, 0, 0);                          //starts parsing commands
    }

return 0;
}<commit_msg>commiting so tests can be added in<commit_after>#include <iostream>
#include <string>
#include <string.h>
#include <typeinfo>
#include <boost/tokenizer.hpp>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
#include <stack>

using namespace std;
using namespace boost;

void Print(vector<string> pts);

void Build_Paren(vector<string> &P_str, int &P_sz, int &Paren_sz);
//Par_prev_prev = Par previous prev or the previous connection
// Par_prev = the next connection

int execute(vector<string> s_t_e, bool &prev, bool &prev_prev, int con, int prev_con, bool Par_prev, bool Par_prev_prev, int Par_connn, int Par_connnn_prev, int paren_size_e, bool in_paren_e, int parseSize){
   //pass in the command and previous
   //cout << "PAR_prev: " << Par_prev << endl;
   //cout << "PAR_prev_prev: " << Par_prev_prev << endl;
   //cout << "PAR_CONNECTION: " << Par_connnn_prev << endl;
   //cout << "connection: " << con << endl;
   char** args = new char*[128];                        //creates new array to store the characters
    for(int i = 0; i < parseSize; i++){
        char * temp = strdup(s_t_e.at(i).c_str());
        args[i] = temp;
    }
    args[parseSize] = '\0';

   if(in_paren_e == true){
   //cout << "IN PAREN executing: \n";

    if((Par_prev == false) && (con != 2) && (Par_connnn_prev != 2))                //may need to get rid of the last condition
    {
        //cout << "FAIL 1: \n";
        return EXIT_FAILURE;
    }
    if((Par_prev == true) && (Par_connnn_prev == 2)){        //might need just par_prev_prev
        //cout << "FAIL 2: \n";
        return EXIT_FAILURE;
    }
   }
    if((prev == false) && (con != 2) && (prev_con != 2)){                //check if the last one was false
    //cout << "FAILED normal: \n";
        return EXIT_FAILURE;              //will/should only work for &&
    }
    if((prev == true) && (prev_con == 2)){
        //cout << "FAILED normal: \n";
      return 0;//EXIT_FAILURE;
    }
        if (strcmp(args[0], "exit") == 0){    //if exit is the command
        exit(0);                          //then exit
    }
    pid_t pid = fork();                   //start forking
        if (pid == -1){                       //fail to fork error
            perror("failed to fork");
            return EXIT_FAILURE;
    }
    else if(pid == 0){                     //start the process
        if(execvp(args[0], args) == -1){   //checks to see if it failed
            perror("execvp");              //if so output error and exit
	          exit(1);
	          return EXIT_FAILURE;
        }
    }
    int status;
    if ( waitpid(pid, &status, 0) == -1 ) { //waitpid waits(not sure what it does)
        perror("waitpid failed");
        exit(1);
        return EXIT_FAILURE;
    }
    if(WIFEXITED(status)){               //always goes into here(I think so)
        const int es = WEXITSTATUS(status);  // checks what the exit was
        //cout << "ES " << es << endl;
	      if(es != 0){                               //if exit was 1 then it failed(IMPORTANT)
		        return EXIT_FAILURE;
        }
    }
return EXIT_SUCCESS;                         //else return 0 for true
}

void Parse(vector<string> &ParseString, int size, bool P_previous, bool P_previous_prev, int P_conn, int P_conn_prev, bool Par_previous, bool Par_previous_prev, int Par_conn, int Par_conn_prev, int Par_conn_next, int &Paren_size, bool in_paren){
if(size < 1){                                       //passing in nothing = return
    return;
}
cout << in_paren << endl;
if((P_conn == 3) && (in_paren != true)){                        //////May need to change this back, erase in paren
    cout << "RESETTING: \n";
    Par_previous = true;
    Par_previous_prev = false;
}
int paren_size = Paren_size;
if(paren_size <= 0){
    in_paren = false;
    paren_size = 0;
}

if(in_paren == false){
    //cout << "changing par connection: \n";
    Par_conn_prev = P_conn;
}

if(ParseString.at(0).at(0) == '('){
    //cout << "parenthesis: " << endl;
    in_paren = true;
    if(in_paren == true){
        Build_Paren(ParseString, size, paren_size);
    }
}
//Print(ParseString);
//cout << endl;
//cout << "SIZE: " << paren_size << endl;

int ParseSize;                                      // will need variables for later
string connector;                                   //will hold the ;/&&/||

int Par_con = Par_conn_next;
int Par_con_next = Par_conn_next;

int Par_con_prev = Par_conn_prev;

int P_con_prev = P_conn;
int P_con;

unsigned i = 0;                                     //basic counter
vector<string> S_T_E;                               //empty vector to be filled in

while((i < ParseString.size())
    && (ParseString.at(i) != ";")                   //creates the string
    && (ParseString.at(i) != "||")                  //that will execute
    && (ParseString.at(i) != "&&")){                //stops when connector/empty
        S_T_E.push_back(ParseString.at(i));
        ++i;
        ParseSize = i;
    }

string SP = ParseString.at(0);                       //if input is ;/&&/|| then error
    if((SP == ";") || (SP == "||") || (SP == "&&")){
        ParseString.erase(ParseString.begin(), ParseString.end());  //delete full string
        cout << "bash: syntax error near unexpected token '" <<  SP << "'" << endl;
        return;
    }

        if(i == ((ParseString.size()))){            //checks the last character
           connector = "0";
           P_con = 0;                        // 0 connector
           //cout << " in 0" << endl;
        }                                           //sets connnector
        else if(ParseString.at(i) == "&&"){         //&& connector
              connector = "&&";
              P_con = 1;
              //cout << " in &&" << endl;
        }
        else if(ParseString.at(i) == "||"){         //|| connector
              connector = "||";
              P_con = 2;
              //cout << " in ||" << endl;
        }
        else if(ParseString.at(i) == ";"){          // ; connector
              connector = ";";
              P_con = 3;
              //cout << " in ;" << endl;
        }

if(ParseSize > 126){                             // limit of 127 strings as one command
        cout << "INPUT TOO LARGE" << endl;
        return;
    }
/*
char** args = new char*[128];                        //creates new array to store the characters
    for(int i = 0; i < ParseSize; i++){
        char * temp = strdup(S_T_E.at(i).c_str());
        args[i] = temp;
    }
*/
    cout << "Executing this string: \n";
    Print(S_T_E);
    cout << endl;
    cout << "END STRING: \n";
    //args[ParseSize] = '\0';                          // null terminating character at the end

    //cout << "Par previous: " << Par_previous << endl;
    //cout << "Par previous previous: " << Par_previous_prev << endl;
    int temp;
    //cout << S_T_E.at(0) << S_T_E.at(ParseSize - 1) << endl;
    if((S_T_E.at(0) == "test") || ((S_T_E.at(0) == "[") && (S_T_E.at(ParseSize - 1) == "]"))){
        cout << "Create test  case: \n";
    }
    //INERT MAGIC HERE
    else{
    temp = execute(S_T_E, P_previous, P_previous_prev, P_con, P_con_prev, Par_previous, Par_previous_prev, Par_con, Par_con_prev, paren_size, in_paren, ParseSize);              //checks whether it executed or not
    }

    //bool Par_temp = P_previous_prev;                //might need to edit this
    P_previous_prev = P_previous;

    if(temp == 0){                                  // sets out boolean P_previous
        P_previous = true;
    }
    else{
        P_previous = false;
    }
    //if(in_paren == true){
    //    Par_previous = P_previous;
    //}
    //else{
    //    Par_previous = Par_temp;                 //FIX HERE
    //}
    //Par_previous_prev

    if(in_paren != true){
        Par_con_next = P_con_prev;
    }

    if(in_paren != true){
    //cout << "changing par previous: \n ";
        Par_previous = P_previous;
    }
        if(connector == "0"){                   //should be empty but parse will handle it
            ParseString.erase(ParseString.begin(), ParseString.begin() + i);
            if(in_paren == true){
                paren_size = paren_size - i;
                    if(paren_size <= 0){
                        Par_con_prev = Par_con_next;
                        Par_con_next = 0;
                         Par_previous = P_previous;
                    }
            }
            //cout << Par_con_prev << " " << Par_con << " " << P_con << endl;

            P_previous = true;
            Parse(ParseString, ParseString.size(), P_previous, P_previous_prev, P_con, P_con_prev, Par_previous, Par_previous_prev, Par_con, Par_con_prev,  Par_con_next, paren_size, in_paren);
        }
        if(connector == "&&"){                   //&& case(only one not set to true*******)
            ParseString.erase(ParseString.begin(), ParseString.begin() + i + 1);
            if(in_paren == true){
                paren_size = paren_size - i - 1;
                    if(paren_size <= 0){
                        Par_con_prev = Par_con_next;
                        Par_con_next = 1;
                        Par_previous = P_previous;
                    }
            }
            //cout << Par_con_prev << " " << Par_con << " " << P_con << endl;

            Parse(ParseString, ParseString.size(), P_previous, P_previous_prev, P_con, P_con_prev, Par_previous, Par_previous_prev, Par_con, Par_con_prev,  Par_con_next, paren_size, in_paren);
        }
        if(connector == "||"){                   //|| case
            ParseString.erase(ParseString.begin(), ParseString.begin() + i + 1);
            if(in_paren == true){
                paren_size = paren_size - i - 1;
                    if(paren_size <= 0){
                        Par_con_prev = Par_con_next;
                        Par_con_next = 2;
                        Par_previous = P_previous;
                    }
            }
            //cout << Par_con_prev << " " << Par_con << " " << P_con << endl;

            if((P_previous_prev == true) && (P_con_prev == 2)){
            P_previous = true;
            }
            Parse(ParseString, ParseString.size(), P_previous, P_previous_prev, P_con, P_con_prev, Par_previous, Par_previous_prev, Par_con, Par_con_prev, Par_con_next, paren_size, in_paren);
        }
        if(connector == ";"){                    //; case
            ParseString.erase(ParseString.begin(), ParseString.begin() + i + 1);
            if(in_paren == true){
                paren_size = paren_size - i - 1;
                    if(paren_size <= 0){
                        Par_con_prev = Par_con_next;
                        Par_con_next = 3;
                         Par_previous = P_previous;
                    }
            }
            //cout << Par_con_prev << " " << Par_con << " " << P_con << endl;

            P_previous = true;
            Parse(ParseString, ParseString.size(),  P_previous, P_previous_prev, P_con, P_con_prev, Par_previous, Par_previous_prev, Par_con, Par_con_prev, Par_con_next, paren_size, in_paren);
        }
        return;
}
//////////////////////IGNORE THIS CODE, JUST DELETES THE COMMENT AND PRINTS////////////////////////////////////
void string_check(string &s, bool &Is_Comment){//helper function for the comment delete
        for(unsigned i = 0; i < s.size(); ++i){
            char temp = s.at(i);               //takes in a string
            if(temp == '#'){                   //compares it to the #
                Is_Comment = false;            //if true then set flag/boolean
            }
        }
}
void Delete_Comment(vector<string> &CC){       //takes in our full vector
        vector<string>::iterator it;           //iterates through the vector
        bool Comment_Checker = true;
        int i = 0;
       	for(it = CC.begin(); it != CC.end(); ++it){
       	    string test = "";
            test = *it;
            ++i;
            string str(test);                   //passes each individual string
            string_check(test, Comment_Checker);//to our helper function
            if(Comment_Checker == false){       //deletes everything past the #
                CC.erase(CC.begin() + i - 1, CC.end());
                return;
            }
       	}
}
void Print(vector<string> pts){                  //function that prints string vector
	vector<string>::iterator it;                   //helped when doing the first steps
	    for(it = pts.begin(); it != pts.end(); ++it){
      cout << *it << " ";                      //not really needed(the print function)
      }
}

bool Prec_checker(vector<string> prec){
stack<char>  S;
	for(unsigned j = 0; j < prec.size(); ++j){
    for(unsigned i = 0; i < prec.at(j).size(); ++i){
		if(prec.at(j).at(i) == '(')
			S.push(prec.at(j).at(i));

		else if(prec.at(j).at(i) == ')'){
			if(S.empty())
				return false;
			else
				S.pop();
		}
   }
	}
	return S.empty() ? true:false;
}

void erase_end_paren(string &s, bool &end_par){
    for(unsigned i = 0; i < s.size(); ++i){
        if(s.at(i) == ')'){
            s.erase(s.begin()+i, s.end());
            end_par = true;
        }
    }
}

void Build_Paren(vector<string> &P_str, int &P_sz, int &Paren_sz){
string temp = P_str.at(0);
temp.erase(temp.begin());

P_str.at(0) = temp;
vector<string> change_parse;
bool build_end_par = false;
for(int i = 0; i < P_sz; ++i)
{
    if(build_end_par == false){
        string find_end = P_str.at(i);
        erase_end_paren(find_end, build_end_par);
        change_parse.push_back(find_end);
        Paren_sz = i + 1;
    }
    else{
        string find_finish = P_str.at(i);
        change_parse.push_back(find_finish);
    }
}
P_str = change_parse;
}

//////////////////////IGNORE THIS CODE, JUST DELETES THE COMMENT, CHECKS PARANTHESIS BALANCE, AND PRINTS////////////////////////////////////

int main(){

bool MainPrevious = true;   //allows us to run our first command
bool MainPrevious_prev = false;

bool Par_MainPrevious = true;   //allows us to run our first command
bool Par_MainPrevious_prev = false;

bool in_paren = false;
int Begin_size = 0;
vector<string> cmd;         //vector to hold our string
string str;                 //will simply be our input string

while(1){
    cout << "$ ";                                           //outputs the $ every iteration

    cmd.erase(cmd.begin(), cmd.end());
    getline(cin, str);                                      //gets input from user
    char_separator<char> delim(" ", ";" "#");               // parameters for our input
    tokenizer< char_separator<char> > mytok(str, delim);

    for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); ++it){
    cmd.push_back(*it);                                     //push to our cmd vector
    }

    Delete_Comment(cmd);                                     // checks for #
    bool done = Prec_checker(cmd);                                       //makes sure even number of precedence
    if(done == false){
    cout << "unmatched paranthesis: " << endl;
    cmd.erase(cmd.begin(), cmd.end());
    }
    int size = cmd.size();                                   //gets updated size(if changed)
    Parse(cmd, size, MainPrevious, MainPrevious_prev, 0, 0,  Par_MainPrevious, Par_MainPrevious_prev, 0, 0, 0, Begin_size, in_paren);                          //starts parsing commands
    }

return 0;
}<|endoftext|>


<commit_before>#include <GLFW/glfw3.h>

#include "PhysSystem.h"

#include "microprofile/microprofile.h"
#include "microprofile/microprofileui.h"

struct Vertex
{
    Vector2f position;
    unsigned char r, g, b, a;

};

void RenderBox(std::vector<Vertex>& vertices, Coords2f coords, Vector2f size, int r, int g, int b, int a)
{
    Vector2f axisX = coords.xVector * size.x;
    Vector2f axisY = coords.yVector * size.y;

    Vertex v;

    v.r = r;
    v.g = g;
    v.b = b;
    v.a = a;

    v.position = coords.pos - axisX - axisY;
    vertices.push_back(v);

    v.position = coords.pos + axisX - axisY;
    vertices.push_back(v);

    v.position = coords.pos + axisX + axisY;
    vertices.push_back(v);

    v.position = coords.pos - axisX + axisY;
    vertices.push_back(v);
}

float random(float min, float max)
{
    return min + (max - min) * (float(rand()) / float(RAND_MAX));
}

const struct
{
    PhysSystem::SolveMode mode;
    const char* name;
} kModes[] =
    {
     {PhysSystem::Solve_Baseline, "Baseline"},
     {PhysSystem::Solve_AoS, "AoS"},
     {PhysSystem::Solve_SoA_Scalar, "SoA Scalar"},
     {PhysSystem::Solve_SoA_SSE2, "SoA SSE2"},

#ifdef __AVX2__
     {PhysSystem::Solve_SoA_AVX2, "SoA AVX2"},
#endif

     {PhysSystem::Solve_SoAPacked_Scalar, "SoA Packed Scalar"},
     {PhysSystem::Solve_SoAPacked_SSE2, "SoA Packed SSE2"},

#ifdef __AVX2__
     {PhysSystem::Solve_SoAPacked_AVX2, "SoA Packed AVX2"},
#endif

#if defined(__AVX2__) && defined(__FMA__)
     {PhysSystem::Solve_SoAPacked_FMA, "SoA Packed FMA"},
#endif
};

bool keyPressed[GLFW_KEY_LAST + 1];
int mouseScrollDelta = 0;

static void errorCallback(int error, const char* description)
{
    fputs(description, stderr);
}

static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    keyPressed[key] = (action == GLFW_PRESS);
}

static void scrollCallback(GLFWwindow* window, double x, double y)
{
    mouseScrollDelta = y;
}

void MicroProfileDrawInit();
void MicroProfileBeginDraw();
void MicroProfileEndDraw();

int main(int argc, char** argv)
{
    MicroProfileOnThreadCreate("Main");

    int windowWidth = 1280, windowHeight = 1024;

    std::unique_ptr<WorkQueue> queue(new WorkQueue(WorkQueue::getIdealWorkerCount()));

    PhysSystem physSystem;

    RigidBody* groundBody = physSystem.AddBody(Coords2f(Vector2f(0, 0), 0.0f), Vector2f(10000.f, 10.0f));
    groundBody->invInertia = 0.0f;
    groundBody->invMass = 0.0f;

    int currentMode = sizeof(kModes) / sizeof(kModes[0]) - 1;

    const float gravity = -200.0f;
    const float integrationTime = 1 / 60.f;
    const int contactIterationsCount = 15;
    const int penetrationIterationsCount = 15;

    physSystem.gravity = gravity;

    physSystem.AddBody(Coords2f(Vector2f(-500, 500), 0.0f), Vector2f(30.0f, 30.0f));

    float bodyRadius = 2.f;
    int bodyCount = 20000;

    for (int bodyIndex = 0; bodyIndex < bodyCount; bodyIndex++)
    {
        Vector2f pos = Vector2f(random(-500.0f, 500.0f), random(50.f, 1000.0f));
        Vector2f size(bodyRadius * 2.f, bodyRadius * 2.f);

        physSystem.AddBody(Coords2f(pos, 0.f), size);
    }

    if (argc > 1 && strcmp(argv[1], "profile") == 0)
    {
        for (int mode = 0; mode < sizeof(kModes) / sizeof(kModes[0]); ++mode)
        {
            PhysSystem testSystem;

            testSystem.gravity = gravity;

            for (auto& body: physSystem.bodies)
            {
                RigidBody* testBody = testSystem.AddBody(body.coords, body.geom.size);
                testBody->invInertia = body.invInertia;
                testBody->invMass = body.invMass;
            }

            double collisionTime = 0;
            double mergeTime = 0;
            double solveTime = 0;
            float iterations = 0;

            for (int i = 0; i < 50; ++i)
            {
                testSystem.Update(*queue, 1.f / 30.f, kModes[mode].mode, contactIterationsCount, penetrationIterationsCount);

                collisionTime += testSystem.collisionTime;
                mergeTime += testSystem.mergeTime;
                solveTime += testSystem.solveTime;
                iterations += testSystem.iterations;
            }

            printf("%s: collision %.2f ms, merge %.2f ms, solve %.2f ms, %.2f iterations\n", kModes[mode].name, collisionTime * 1000, mergeTime * 1000, solveTime * 1000, iterations);
        }

        return 0;
    }

    glfwSetErrorCallback(errorCallback);

    if (!glfwInit()) return 1;

    GLFWwindow* window = glfwCreateWindow(windowWidth, windowHeight, "PhyX", NULL, NULL);
    if (!window) return 1;

    glfwMakeContextCurrent(window);
    glfwSwapInterval(0);
    glfwSetKeyCallback(window, keyCallback);
    glfwSetScrollCallback(window, scrollCallback);

    MicroProfileDrawInit();

    double prevUpdateTime = 0.0f;

    std::vector<Vertex> vertices;

    while (!glfwWindowShouldClose(window))
    {
        MICROPROFILE_SCOPEI("MAIN", "Frame", 0xffee00);

        int width, height;
        glfwGetWindowSize(window, &width, &height);

        int frameWidth, frameHeight;
        glfwGetFramebufferSize(window, &frameWidth, &frameHeight);

        double mouseX, mouseY;
        glfwGetCursorPos(window, &mouseX, &mouseY);

        glViewport(0, 0, frameWidth, frameHeight);
        glClearColor(0.2f, 0.2f, 0.2f, 1.f);
        glClear(GL_COLOR_BUFFER_BIT);

        float offsetx = -width / 2;
        float offsety = -40;
        float scale = 0.5f;

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(offsetx / scale, width / scale + offsetx / scale, offsety / scale, height / scale + offsety / scale, 1.f, -1.f);

        vertices.clear();

        if (glfwGetTime() > prevUpdateTime + integrationTime)
        {
            prevUpdateTime += integrationTime;

            float time = integrationTime;

            Vector2f mousePos = Vector2f(mouseX + offsetx, height + offsety - mouseY) / scale;

            RigidBody* draggedBody = &physSystem.bodies[1];
            Vector2f dstVelocity = (mousePos - draggedBody->coords.pos) * 5e1f;
            draggedBody->acceleration += (dstVelocity - draggedBody->velocity) * 5e0;

            physSystem.Update(*queue, time, kModes[currentMode].mode, contactIterationsCount, penetrationIterationsCount);
        }

        {
            MICROPROFILE_SCOPEI("Render", "Prepare", 0xff0000);

            for (size_t bodyIndex = 0; bodyIndex < physSystem.bodies.size(); bodyIndex++)
            {
                RigidBody* body = &physSystem.bodies[bodyIndex];
                Coords2f bodyCoords = body->coords;
                Vector2f size = body->geom.size;

                float colorMult = float(bodyIndex) / float(physSystem.bodies.size()) * 0.5f + 0.5f;
                int r = 50 * colorMult;
                int g = 125 * colorMult;
                int b = 218 * colorMult;

                if (bodyIndex == 1) //dragged body
                {
                    r = 242;
                    g = 236;
                    b = 164;
                }

                RenderBox(vertices, bodyCoords, size, r, g, b, 255);
            }

            if (glfwGetKey(window, GLFW_KEY_V))
            {
                for (size_t manifoldIndex = 0; manifoldIndex < physSystem.collider.manifolds.size(); manifoldIndex++)
                {
                    Manifold& man = physSystem.collider.manifolds[manifoldIndex];

                    for (int collisionNumber = 0; collisionNumber < man.collisionsCount; collisionNumber++)
                    {
                        Coords2f coords = Coords2f(Vector2f(0.0f, 0.0f), 3.1415f / 4.0f);

                        coords.pos = man.body1->coords.pos + man.collisions[collisionNumber].delta1;

                        float redMult = man.collisions[collisionNumber].isNewlyCreated ? 0.5f : 1.0f;

                        RenderBox(vertices, coords, Vector2f(3.0f, 3.0f), 100, 100 * redMult, 100 * redMult, 100);

                        coords.pos = man.body2->coords.pos + man.collisions[collisionNumber].delta2;

                        RenderBox(vertices, coords, Vector2f(3.0f, 3.0f), 150, 150 * redMult, 150 * redMult, 100);
                    }
                }
            }
        }

        {
            MICROPROFILE_SCOPEI("Render", "Perform", 0xff0000);

            if (!vertices.empty())
            {
                glEnableClientState(GL_VERTEX_ARRAY);
                glEnableClientState(GL_COLOR_ARRAY);

                glVertexPointer(2, GL_FLOAT, sizeof(Vertex), &vertices[0].position);
                glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), &vertices[0].r);

                glDrawArrays(GL_QUADS, 0, vertices.size());

                glDisableClientState(GL_VERTEX_ARRAY);
                glDisableClientState(GL_COLOR_ARRAY);
            }
        }

        char stats[256];
        sprintf(stats, "Bodies: %d Manifolds: %d Contacts: %d | Cores: %d; Mode: %s; Iterations: %.2f",
            int(physSystem.bodies.size()),
            int(physSystem.collider.manifolds.size()),
            int(physSystem.solver.contactJoints.size()),
            int(queue->getWorkerCount()),
            kModes[currentMode].name,
            physSystem.iterations);

        MicroProfileFlip();

        {
            glMatrixMode(GL_PROJECTION);
            glLoadIdentity();
            glOrtho(0, width, height, 0, 1.f, -1.f);

            glEnable(GL_BLEND);
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            glDisable(GL_DEPTH_TEST);

            MicroProfileBeginDraw();

            MicroProfileDraw(width, height);
            MicroProfileDrawText(2, height - 12, 0xffffffff, stats, strlen(stats));

            MicroProfileEndDraw();

            glDisable(GL_BLEND);
        }

        {
            MICROPROFILE_SCOPEI("MAIN", "Flip", 0xffee00);

            glfwSwapBuffers(window);
        }

        {
            MICROPROFILE_SCOPEI("MAIN", "Input", 0xffee00);

            // Handle input
            memset(keyPressed, 0, sizeof(keyPressed));
            mouseScrollDelta = 0;

            glfwPollEvents();

            bool mouseDown0 = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS;
            bool mouseDown1 = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS;

            MicroProfileMouseButton(mouseDown0, mouseDown1);
            MicroProfileMousePosition(mouseX, mouseY, mouseScrollDelta);
            MicroProfileModKey(glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS);

            if (keyPressed[GLFW_KEY_ESCAPE])
                break;

            if (keyPressed[GLFW_KEY_O])
                MicroProfileToggleDisplayMode();

            if (keyPressed[GLFW_KEY_P])
                MicroProfileTogglePause();

            if (keyPressed[GLFW_KEY_M])
                currentMode = (currentMode + 1) % (sizeof(kModes) / sizeof(kModes[0]));

            if (keyPressed[GLFW_KEY_C])
            {
                size_t workers =
                    (queue->getWorkerCount() == WorkQueue::getIdealWorkerCount())
                    ? 1
                    : std::min(queue->getWorkerCount() * 2, WorkQueue::getIdealWorkerCount());

                queue.reset(new WorkQueue(workers));
            }
        }
    }

    glfwDestroyWindow(window);
    glfwTerminate();
}<commit_msg>Add world resetting and scene switching<commit_after>#include <GLFW/glfw3.h>

#include "PhysSystem.h"

#include "microprofile/microprofile.h"
#include "microprofile/microprofileui.h"

struct Vertex
{
    Vector2f position;
    unsigned char r, g, b, a;

};

void RenderBox(std::vector<Vertex>& vertices, Coords2f coords, Vector2f size, int r, int g, int b, int a)
{
    Vector2f axisX = coords.xVector * size.x;
    Vector2f axisY = coords.yVector * size.y;

    Vertex v;

    v.r = r;
    v.g = g;
    v.b = b;
    v.a = a;

    v.position = coords.pos - axisX - axisY;
    vertices.push_back(v);

    v.position = coords.pos + axisX - axisY;
    vertices.push_back(v);

    v.position = coords.pos + axisX + axisY;
    vertices.push_back(v);

    v.position = coords.pos - axisX + axisY;
    vertices.push_back(v);
}

float random(float min, float max)
{
    return min + (max - min) * (float(rand()) / float(RAND_MAX));
}

const struct
{
    PhysSystem::SolveMode mode;
    const char* name;
} kModes[] =
    {
     {PhysSystem::Solve_Baseline, "Baseline"},
     {PhysSystem::Solve_AoS, "AoS"},
     {PhysSystem::Solve_SoA_Scalar, "SoA Scalar"},
     {PhysSystem::Solve_SoA_SSE2, "SoA SSE2"},

#ifdef __AVX2__
     {PhysSystem::Solve_SoA_AVX2, "SoA AVX2"},
#endif

     {PhysSystem::Solve_SoAPacked_Scalar, "SoA Packed Scalar"},
     {PhysSystem::Solve_SoAPacked_SSE2, "SoA Packed SSE2"},

#ifdef __AVX2__
     {PhysSystem::Solve_SoAPacked_AVX2, "SoA Packed AVX2"},
#endif

#if defined(__AVX2__) && defined(__FMA__)
     {PhysSystem::Solve_SoAPacked_FMA, "SoA Packed FMA"},
#endif
};

const char* resetWorld(PhysSystem& world, int scene)
{
    world.bodies.clear();
    world.collider.manifolds.clear();
    world.collider.manifoldMap.clear();
    world.solver.contactJoints.clear();

    RigidBody* groundBody = world.AddBody(Coords2f(Vector2f(0, 0), 0.0f), Vector2f(10000.f, 10.0f));
    groundBody->invInertia = 0.0f;
    groundBody->invMass = 0.0f;

    world.AddBody(Coords2f(Vector2f(-1000, 1000), 0.0f), Vector2f(30.0f, 30.0f));

    switch (scene % 2)
    {
    case 0:
    {
        for (int bodyIndex = 0; bodyIndex < 20000; bodyIndex++)
        {
            Vector2f pos = Vector2f(random(-500.0f, 500.0f), random(50.f, 1000.0f));
            Vector2f size(4.f, 4.f);

            world.AddBody(Coords2f(pos, 0.f), size);
        }

        return "Falling";
    }

    case 1:
    {
        for (int left = -100; left <= 100; left++)
        {
            for (int bodyIndex = 0; bodyIndex < 100; bodyIndex++)
            {
                Vector2f pos = Vector2f(left * 20, 10 + bodyIndex * 10);
                Vector2f size(10, 5);

                world.AddBody(Coords2f(pos, 0.f), size);
            }
        }

        return "Wall";
    }
    }

    return "Empty";
}

bool keyPressed[GLFW_KEY_LAST + 1];
int mouseScrollDelta = 0;

static void errorCallback(int error, const char* description)
{
    fputs(description, stderr);
}

static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    keyPressed[key] = (action == GLFW_PRESS);
}

static void scrollCallback(GLFWwindow* window, double x, double y)
{
    mouseScrollDelta = y;
}

void MicroProfileDrawInit();
void MicroProfileBeginDraw();
void MicroProfileEndDraw();

int main(int argc, char** argv)
{
    MicroProfileOnThreadCreate("Main");

    int windowWidth = 1280, windowHeight = 1024;

    std::unique_ptr<WorkQueue> queue(new WorkQueue(WorkQueue::getIdealWorkerCount()));

    PhysSystem physSystem;

    int currentMode = sizeof(kModes) / sizeof(kModes[0]) - 1;
    int currentScene = 0;

    const char* currentSceneName = resetWorld(physSystem, currentScene);

    const float gravity = -200.0f;
    const float integrationTime = 1 / 60.f;
    const int contactIterationsCount = 15;
    const int penetrationIterationsCount = 15;

    physSystem.gravity = gravity;

    if (argc > 1 && strcmp(argv[1], "profile") == 0)
    {
        for (int mode = 0; mode < sizeof(kModes) / sizeof(kModes[0]); ++mode)
        {
            PhysSystem testSystem;

            testSystem.gravity = gravity;

            for (auto& body: physSystem.bodies)
            {
                RigidBody* testBody = testSystem.AddBody(body.coords, body.geom.size);
                testBody->invInertia = body.invInertia;
                testBody->invMass = body.invMass;
            }

            double collisionTime = 0;
            double mergeTime = 0;
            double solveTime = 0;
            float iterations = 0;

            for (int i = 0; i < 50; ++i)
            {
                testSystem.Update(*queue, 1.f / 30.f, kModes[mode].mode, contactIterationsCount, penetrationIterationsCount);

                collisionTime += testSystem.collisionTime;
                mergeTime += testSystem.mergeTime;
                solveTime += testSystem.solveTime;
                iterations += testSystem.iterations;
            }

            printf("%s: collision %.2f ms, merge %.2f ms, solve %.2f ms, %.2f iterations\n", kModes[mode].name, collisionTime * 1000, mergeTime * 1000, solveTime * 1000, iterations);
        }

        return 0;
    }

    glfwSetErrorCallback(errorCallback);

    if (!glfwInit()) return 1;

    GLFWwindow* window = glfwCreateWindow(windowWidth, windowHeight, "PhyX", NULL, NULL);
    if (!window) return 1;

    glfwMakeContextCurrent(window);
    glfwSwapInterval(0);
    glfwSetKeyCallback(window, keyCallback);
    glfwSetScrollCallback(window, scrollCallback);

    MicroProfileDrawInit();

    bool paused = false;

    double prevUpdateTime = 0.0f;

    std::vector<Vertex> vertices;

    while (!glfwWindowShouldClose(window))
    {
        MicroProfileFlip();

        MICROPROFILE_SCOPEI("MAIN", "Frame", 0xffee00);

        int width, height;
        glfwGetWindowSize(window, &width, &height);

        int frameWidth, frameHeight;
        glfwGetFramebufferSize(window, &frameWidth, &frameHeight);

        double mouseX, mouseY;
        glfwGetCursorPos(window, &mouseX, &mouseY);

        glViewport(0, 0, frameWidth, frameHeight);
        glClearColor(0.2f, 0.2f, 0.2f, 1.f);
        glClear(GL_COLOR_BUFFER_BIT);

        float offsetx = -width / 2;
        float offsety = -40;
        float scale = 0.5f;

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(offsetx / scale, width / scale + offsetx / scale, offsety / scale, height / scale + offsety / scale, 1.f, -1.f);

        vertices.clear();

        if (glfwGetTime() > prevUpdateTime + integrationTime)
        {
            prevUpdateTime += integrationTime;

            if (!paused)
            {
                Vector2f mousePos = Vector2f(mouseX + offsetx, height + offsety - mouseY) / scale;

                RigidBody* draggedBody = &physSystem.bodies[1];
                Vector2f dstVelocity = (mousePos - draggedBody->coords.pos) * 5e1f;
                draggedBody->acceleration += (dstVelocity - draggedBody->velocity) * 5e0;

                physSystem.Update(*queue, integrationTime, kModes[currentMode].mode, contactIterationsCount, penetrationIterationsCount);
            }
        }

        char stats[256];
        sprintf(stats, "Scene: %s | Bodies: %d Manifolds: %d Contacts: %d | Cores: %d; Mode: %s; Iterations: %.2f",
            currentSceneName,
            int(physSystem.bodies.size()),
            int(physSystem.collider.manifolds.size()),
            int(physSystem.solver.contactJoints.size()),
            int(queue->getWorkerCount()),
            kModes[currentMode].name,
            physSystem.iterations);

        {
            MICROPROFILE_SCOPEI("Render", "Render", 0xff0000);

            {
                MICROPROFILE_SCOPEI("Render", "Prepare", -1);

                for (size_t bodyIndex = 0; bodyIndex < physSystem.bodies.size(); bodyIndex++)
                {
                    RigidBody* body = &physSystem.bodies[bodyIndex];
                    Coords2f bodyCoords = body->coords;
                    Vector2f size = body->geom.size;

                    float colorMult = float(bodyIndex) / float(physSystem.bodies.size()) * 0.5f + 0.5f;
                    int r = 50 * colorMult;
                    int g = 125 * colorMult;
                    int b = 218 * colorMult;

                    if (bodyIndex == 1) //dragged body
                    {
                        r = 242;
                        g = 236;
                        b = 164;
                    }

                    RenderBox(vertices, bodyCoords, size, r, g, b, 255);
                }

                if (glfwGetKey(window, GLFW_KEY_V))
                {
                    for (size_t manifoldIndex = 0; manifoldIndex < physSystem.collider.manifolds.size(); manifoldIndex++)
                    {
                        Manifold& man = physSystem.collider.manifolds[manifoldIndex];

                        for (int collisionNumber = 0; collisionNumber < man.collisionsCount; collisionNumber++)
                        {
                            Coords2f coords = Coords2f(Vector2f(0.0f, 0.0f), 3.1415f / 4.0f);

                            coords.pos = man.body1->coords.pos + man.collisions[collisionNumber].delta1;

                            float redMult = man.collisions[collisionNumber].isNewlyCreated ? 0.5f : 1.0f;

                            RenderBox(vertices, coords, Vector2f(3.0f, 3.0f), 100, 100 * redMult, 100 * redMult, 100);

                            coords.pos = man.body2->coords.pos + man.collisions[collisionNumber].delta2;

                            RenderBox(vertices, coords, Vector2f(3.0f, 3.0f), 150, 150 * redMult, 150 * redMult, 100);
                        }
                    }
                }
            }

            {
                MICROPROFILE_SCOPEI("Render", "Perform", -1);

                if (!vertices.empty())
                {
                    glEnableClientState(GL_VERTEX_ARRAY);
                    glEnableClientState(GL_COLOR_ARRAY);

                    glVertexPointer(2, GL_FLOAT, sizeof(Vertex), &vertices[0].position);
                    glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), &vertices[0].r);

                    glDrawArrays(GL_QUADS, 0, vertices.size());

                    glDisableClientState(GL_VERTEX_ARRAY);
                    glDisableClientState(GL_COLOR_ARRAY);
                }
            }

            {
                MICROPROFILE_SCOPEI("Render", "Profile", -1);

                glMatrixMode(GL_PROJECTION);
                glLoadIdentity();
                glOrtho(0, width, height, 0, 1.f, -1.f);

                glEnable(GL_BLEND);
                glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
                glDisable(GL_DEPTH_TEST);

                MicroProfileBeginDraw();

                MicroProfileDraw(width, height);
                MicroProfileDrawText(2, height - 12, 0xffffffff, stats, strlen(stats));

                MicroProfileEndDraw();

                glDisable(GL_BLEND);
            }
        }

        {
            MICROPROFILE_SCOPEI("MAIN", "Flip", 0xffee00);

            glfwSwapBuffers(window);
        }

        {
            MICROPROFILE_SCOPEI("MAIN", "Input", 0xffee00);

            // Handle input
            memset(keyPressed, 0, sizeof(keyPressed));
            mouseScrollDelta = 0;

            glfwPollEvents();

            bool mouseDown0 = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS;
            bool mouseDown1 = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS;

            MicroProfileMouseButton(mouseDown0, mouseDown1);
            MicroProfileMousePosition(mouseX, mouseY, mouseScrollDelta);
            MicroProfileModKey(glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS);

            if (keyPressed[GLFW_KEY_ESCAPE])
                break;

            if (keyPressed[GLFW_KEY_O])
                MicroProfileToggleDisplayMode();

            if (keyPressed[GLFW_KEY_P])
            {
                paused = !paused;
                MicroProfileTogglePause();
            }

            if (keyPressed[GLFW_KEY_M])
                currentMode = (currentMode + 1) % (sizeof(kModes) / sizeof(kModes[0]));

            if (keyPressed[GLFW_KEY_R])
                currentSceneName = resetWorld(physSystem, currentScene);

            if (keyPressed[GLFW_KEY_S])
                currentSceneName = resetWorld(physSystem, ++currentScene);

            if (keyPressed[GLFW_KEY_C])
            {
                size_t workers =
                    (queue->getWorkerCount() == WorkQueue::getIdealWorkerCount())
                    ? 1
                    : std::min(queue->getWorkerCount() * 2, WorkQueue::getIdealWorkerCount());

                queue.reset(new WorkQueue(workers));
            }
        }
    }

    glfwDestroyWindow(window);
    glfwTerminate();
}<|endoftext|>