<commit_before>#include <cmath>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <vector>
#include <SFML/Graphics.hpp>

using std::cerr;
using std::endl;

#define PPB 64
#define DIAM PPB / 4.0
#define RAD PPB / 8.0
#define THICK PPB / 16.0
#define DTHICK PPB / 8.0

sf::RenderTexture tile_texture[26];

class Tile
{
	char character;
	sf::Sprite sprite;
public:
	Tile(char ch) :
		sprite(tile_texture[ch - 'A'].getTexture())
	{
		character = ch;
	}

	char ch() const
	{
		return character;
	}

	void set_pos(int x, int y)
	{
		sprite.setPosition(x * PPB, y * PPB);
	}

	void draw_on(sf::RenderWindow & window) const
	{
		window.draw(sprite);
	}
};

class Grid
{
	std::vector<Tile*> grid;

	inline unsigned int bijection(unsigned x, unsigned int y) const
	{
		return ((x + y) * (x + y + 1)) / 2 + x;
	}

	unsigned int convert(int x, int y) const
	{
		if (x >= 0 && y >= 0)
			return 4 * bijection(x, y);
		if (x < 0 && y >= 0)
			return 4 * bijection(-x - 1, y) + 1;
		if (x >= 0 && y < 0)
			return 4 * bijection(x, -y - 1) + 2;
		else
			return 4 * bijection(-x - 1, -y - 1) + 3;
	}
public:
	Grid() : grid()
	{
	}

	~Grid()
	{
		for (auto tile : grid)
			if (tile != nullptr)
				delete tile;
	}

	Tile* get(int x, int y) const
	{
		unsigned int n = convert(x, y);
		if (n >= grid.size())
			return nullptr;
		return grid[n];
	}

	Tile* remove(int x, int y)
	{
		unsigned int n = convert(x, y);
		if (n < grid.size())
		{
			Tile* tile = grid[n];
			if (tile == nullptr)
				return nullptr;

			grid[n] = nullptr;
			for (n = grid.size(); n --> 0;)
				if (grid[n] != nullptr)
					break;
			// TODO won't ever shrink to 0
			grid.resize(n + 1, nullptr);
			return tile;
		}
		return nullptr;
	}

	Tile* swap(int x, int y, Tile* tile)
	{
		if (tile == nullptr)
			throw std::runtime_error("attempt to place NULL tile");
		unsigned int n = convert(x, y);
		if (n >= grid.size())
			// TODO catch failure?
			grid.resize(n + 1, nullptr);
		Tile* swp = grid[n];
		tile->set_pos(x, y);
		grid[n] = tile;
		return swp;
	}

	void draw_on(sf::RenderWindow& window) const
	{
		for (auto tile : grid)
			if (tile != nullptr)
				tile->draw_on(window);
	}
};

int main()
{
	sf::Font font;
	font.loadFromFile("/usr/share/fonts/TTF/VeraMono.ttf");
	Grid grid;

	unsigned int letter_count[26] =
	{
		13,
		3,
		3,
		6,
		18,
		3,
		4,
		3,
		12,
		2,
		2,
		5,
		3,
		8,
		11,
		3,
		2,
		9,
		6,
		9,
		6,
		3,
		3,
		2,
		3,
		2
	};

	// create textures and tiles
	cerr << "Generating textures...\n";
	std::vector<Tile*> tiles[26];
	for (char ch = 'A'; ch <= 'Z'; ch++)
		tiles[ch - 'A'] = std::vector<Tile*>();
	{
		unsigned int miny = PPB;
		unsigned int maxy = 0;
		bool done_y = false;
		for (char ch = 'A'; ch <= 'Z'; ch++)
		{
			// TODO antialiase these
			// TODO error check
			// TODO memory leak here?
			tile_texture[ch - 'A'].create(PPB, PPB);
			tile_texture[ch - 'A'].clear(sf::Color::Red);

			std::stringstream string;
			string << ch;
			sf::Text letter(string.str(), font, (PPB * 2) / 3.0);
			letter.setColor(sf::Color::Black);
			tile_texture[ch - 'A'].draw(letter);
			tile_texture[ch - 'A'].display();

			// center character
			unsigned int minx = PPB;
			unsigned int maxx = 0;
			auto image = tile_texture[ch - 'A'].getTexture().copyToImage();
			auto size = image.getSize();
			for (unsigned int x = 0; x < size.x; x++)
				for (unsigned int y = 0; y < size.y; y++)
					if (image.getPixel(x, y) != sf::Color::Red)
					{
						if (x < minx)
							minx = x;
						if (x > maxx)
							maxx = x;
						if (!done_y)
						{
							if (y < miny)
								miny = y;
							if (y > maxy)
								maxy = y;
						}
					}
			done_y = true;
			letter.setPosition((PPB - (maxx - minx + 1)) / 2.0 - minx, (PPB - (maxy - miny + 1)) / 2.0 - miny);

			tile_texture[ch - 'A'].clear(sf::Color(0, 0, 0, 0));

			sf::RectangleShape rect;
			rect.setFillColor(sf::Color(255, 255, 175));

			rect.setSize(sf::Vector2f(PPB - DIAM, PPB));
			rect.setPosition(RAD, 0);
			tile_texture[ch - 'A'].draw(rect);
			rect.setSize(sf::Vector2f(PPB, PPB - DIAM));
			rect.setPosition(0, RAD);
			tile_texture[ch - 'A'].draw(rect);

			sf::CircleShape circle(RAD);
			circle.setFillColor(sf::Color(255, 255, 175));

			circle.setPosition(0, 0);
			tile_texture[ch - 'A'].draw(circle);
			circle.setPosition(PPB - DIAM, 0);
			tile_texture[ch - 'A'].draw(circle);
			circle.setPosition(0, PPB - DIAM);
			tile_texture[ch - 'A'].draw(circle);
			circle.setPosition(PPB - DIAM, PPB - DIAM);
			tile_texture[ch - 'A'].draw(circle);

			tile_texture[ch - 'A'].draw(letter);
			tile_texture[ch - 'A'].display();

			for (unsigned int i = 0; i < letter_count[ch - 'A']; i++)
				tiles[ch - 'A'].push_back(new Tile(ch));
		}
	}

	sf::Color background(22, 22, 22);

	sf::RenderWindow window(sf::VideoMode(1024, 600), "Bananagrams", sf::Style::Titlebar);
	sf::View view = window.getDefaultView();
	view.setCenter(PPB / 2.0, PPB / 2.0);
	window.setView(view);

	int pos[2] = {0, 0};
	int delta[2] = {0, 0};
	float held[2] = {0, 0};

	float repeat_delay = 0.5;
	float repeat_speed = 0.1;

	sf::RectangleShape cursor(sf::Vector2f(PPB - DTHICK, PPB - DTHICK));
	cursor.setFillColor(sf::Color(0, 0, 0, 0));
	cursor.setOutlineThickness(THICK);
	cursor.setOutlineColor(sf::Color(0, 200, 0));

	sf::Clock clock;
	bool zoom_key = false;
	bool sprint_key = false;
	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed || (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape))
				window.close();
			else if (event.type == sf::Event::KeyPressed)
			{
				Tile* tile;
				switch (event.key.code)
				{
					case sf::Keyboard::Left:
						delta[0] = -1;
						break;
					case sf::Keyboard::Right:
						delta[0] = 1;
						break;
					case sf::Keyboard::Up:
						delta[1] = -1;
						break;
					case sf::Keyboard::Down:
						delta[1] = 1;
						break;
					case sf::Keyboard::LControl:
					case sf::Keyboard::RControl:
						zoom_key = true;
						break;
					case sf::Keyboard::LShift:
					case sf::Keyboard::RShift:
						sprint_key = true;
						break;
					case sf::Keyboard::BackSpace:
						tile = grid.remove(pos[0], pos[1]);
						if (tile != nullptr)
							tiles[tile->ch() - 'A'].push_back(tile);
						break;
					default:
						break;
				}
				if (sf::Keyboard::A <= event.key.code && event.key.code <= sf::Keyboard::Z)
				{
					if (tiles[event.key.code - sf::Keyboard::A].size() > 0)
					{
						Tile* tile = grid.swap(pos[0], pos[1], tiles[event.key.code - sf::Keyboard::A].back());
						tiles[event.key.code - sf::Keyboard::A].pop_back();
						if (tile != nullptr)
							tiles[tile->ch() - 'A'].push_back(tile);
					}
				}
			}
			else if (event.type == sf::Event::KeyReleased)
			{
				switch (event.key.code)
				{
					case sf::Keyboard::Left:
					case sf::Keyboard::Right:
						delta[0] = 0;
						break;
					case sf::Keyboard::Up:
					case sf::Keyboard::Down:
						delta[1] = 0;
						break;
					case sf::Keyboard::LControl:
					case sf::Keyboard::RControl:
						zoom_key = false;
						break;
					case sf::Keyboard::LShift:
					case sf::Keyboard::RShift:
						sprint_key = false;
						break;
					default:
						break;
				}
			}
		}

		float time = clock.getElapsedTime().asSeconds();
		clock.restart();

		if (zoom_key)
		{
			view.zoom(1 + delta[1] * (sprint_key ? 2 : 1) * time);
		}
		else
		{
			for (unsigned int i = 0; i < 2; i++)
			{
				if (delta[i] == 0)
					held[i] = 0;
				else
				{
					if (held[i] == 0)
						pos[i] += delta[i] * (sprint_key ? 2 : 1);
					else
						while (held[i] > repeat_delay)
						{
							pos[i] += delta[i] * (sprint_key ? 2 : 1);
							held[i] -= repeat_speed;
						}
					held[i] += time;
				}
			}
		}

		auto center = view.getCenter();
		float max = time * 500.0 * (sprint_key ? 2 : 1);
		sf::Vector2f diff(pos[0] * PPB + PPB / 2.0 - center.x, pos[1] * PPB + PPB / 2.0 - center.y);
		float length = std::sqrt(diff.x * diff.x + diff.y * diff.y);
		if (length > max)
		{
			diff.x = (diff.x * max) / length;
			diff.y = (diff.y * max) / length;
		}
		view.move(diff.x, diff.y);
		// don't allow zooming past default
		auto size = view.getSize();
		// TODO bleh hardcoded size
		if (size.x < 1024 || size.y < 600)
			view.setSize(1024, 600);
		window.setView(view);

		cursor.setPosition(pos[0] * PPB + THICK, pos[1] * PPB + THICK);

		window.clear(background);
		grid.draw_on(window);
		window.draw(cursor);

		window.display();
	}

	// delete unused tiles
	for (char ch = 'A'; ch <= 'Z'; ch++)
		for (auto tile: tiles[ch - 'A'])
			delete tile;

	return 0;
}
<commit_msg>Auto-advance cursor<commit_after>#include <cmath>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <vector>
#include <SFML/Graphics.hpp>

using std::cerr;
using std::endl;

#define PPB 64
#define DIAM PPB / 4.0
#define RAD PPB / 8.0
#define THICK PPB / 16.0
#define DTHICK PPB / 8.0

sf::RenderTexture tile_texture[26];

class Tile
{
	char character;
	sf::Sprite sprite;
public:
	Tile(char ch) :
		sprite(tile_texture[ch - 'A'].getTexture())
	{
		character = ch;
	}

	char ch() const
	{
		return character;
	}

	void set_pos(int x, int y)
	{
		sprite.setPosition(x * PPB, y * PPB);
	}

	void draw_on(sf::RenderWindow & window) const
	{
		window.draw(sprite);
	}
};

class Grid
{
	std::vector<Tile*> grid;

	inline unsigned int bijection(unsigned x, unsigned int y) const
	{
		return ((x + y) * (x + y + 1)) / 2 + x;
	}

	unsigned int convert(int x, int y) const
	{
		if (x >= 0 && y >= 0)
			return 4 * bijection(x, y);
		if (x < 0 && y >= 0)
			return 4 * bijection(-x - 1, y) + 1;
		if (x >= 0 && y < 0)
			return 4 * bijection(x, -y - 1) + 2;
		else
			return 4 * bijection(-x - 1, -y - 1) + 3;
	}
public:
	Grid() : grid()
	{
	}

	~Grid()
	{
		for (auto tile : grid)
			if (tile != nullptr)
				delete tile;
	}

	Tile* get(int x, int y) const
	{
		unsigned int n = convert(x, y);
		if (n >= grid.size())
			return nullptr;
		return grid[n];
	}

	Tile* remove(int x, int y)
	{
		unsigned int n = convert(x, y);
		if (n < grid.size())
		{
			Tile* tile = grid[n];
			if (tile == nullptr)
				return nullptr;

			grid[n] = nullptr;
			for (n = grid.size(); n --> 0;)
				if (grid[n] != nullptr)
					break;
			// TODO won't ever shrink to 0
			grid.resize(n + 1, nullptr);
			return tile;
		}
		return nullptr;
	}

	Tile* swap(int x, int y, Tile* tile)
	{
		if (tile == nullptr)
			throw std::runtime_error("attempt to place NULL tile");
		unsigned int n = convert(x, y);
		if (n >= grid.size())
			// TODO catch failure?
			grid.resize(n + 1, nullptr);
		Tile* swp = grid[n];
		tile->set_pos(x, y);
		grid[n] = tile;
		return swp;
	}

	void draw_on(sf::RenderWindow& window) const
	{
		for (auto tile : grid)
			if (tile != nullptr)
				tile->draw_on(window);
	}
};

int main()
{
	sf::Font font;
	font.loadFromFile("/usr/share/fonts/TTF/VeraMono.ttf");
	Grid grid;

	unsigned int letter_count[26] =
	{
		13,
		3,
		3,
		6,
		18,
		3,
		4,
		3,
		12,
		2,
		2,
		5,
		3,
		8,
		11,
		3,
		2,
		9,
		6,
		9,
		6,
		3,
		3,
		2,
		3,
		2
	};

	// create textures and tiles
	cerr << "Generating textures...\n";
	std::vector<Tile*> tiles[26];
	for (char ch = 'A'; ch <= 'Z'; ch++)
		tiles[ch - 'A'] = std::vector<Tile*>();
	{
		unsigned int miny = PPB;
		unsigned int maxy = 0;
		bool done_y = false;
		for (char ch = 'A'; ch <= 'Z'; ch++)
		{
			// TODO antialiase these
			// TODO error check
			// TODO memory leak here?
			tile_texture[ch - 'A'].create(PPB, PPB);
			tile_texture[ch - 'A'].clear(sf::Color::Red);

			std::stringstream string;
			string << ch;
			sf::Text letter(string.str(), font, (PPB * 2) / 3.0);
			letter.setColor(sf::Color::Black);
			tile_texture[ch - 'A'].draw(letter);
			tile_texture[ch - 'A'].display();

			// center character
			unsigned int minx = PPB;
			unsigned int maxx = 0;
			auto image = tile_texture[ch - 'A'].getTexture().copyToImage();
			auto size = image.getSize();
			for (unsigned int x = 0; x < size.x; x++)
				for (unsigned int y = 0; y < size.y; y++)
					if (image.getPixel(x, y) != sf::Color::Red)
					{
						if (x < minx)
							minx = x;
						if (x > maxx)
							maxx = x;
						if (!done_y)
						{
							if (y < miny)
								miny = y;
							if (y > maxy)
								maxy = y;
						}
					}
			done_y = true;
			letter.setPosition((PPB - (maxx - minx + 1)) / 2.0 - minx, (PPB - (maxy - miny + 1)) / 2.0 - miny);

			tile_texture[ch - 'A'].clear(sf::Color(0, 0, 0, 0));

			sf::RectangleShape rect;
			rect.setFillColor(sf::Color(255, 255, 175));

			rect.setSize(sf::Vector2f(PPB - DIAM, PPB));
			rect.setPosition(RAD, 0);
			tile_texture[ch - 'A'].draw(rect);
			rect.setSize(sf::Vector2f(PPB, PPB - DIAM));
			rect.setPosition(0, RAD);
			tile_texture[ch - 'A'].draw(rect);

			sf::CircleShape circle(RAD);
			circle.setFillColor(sf::Color(255, 255, 175));

			circle.setPosition(0, 0);
			tile_texture[ch - 'A'].draw(circle);
			circle.setPosition(PPB - DIAM, 0);
			tile_texture[ch - 'A'].draw(circle);
			circle.setPosition(0, PPB - DIAM);
			tile_texture[ch - 'A'].draw(circle);
			circle.setPosition(PPB - DIAM, PPB - DIAM);
			tile_texture[ch - 'A'].draw(circle);

			tile_texture[ch - 'A'].draw(letter);
			tile_texture[ch - 'A'].display();

			for (unsigned int i = 0; i < letter_count[ch - 'A']; i++)
				tiles[ch - 'A'].push_back(new Tile(ch));
		}
	}

	sf::Color background(22, 22, 22);

	sf::RenderWindow window(sf::VideoMode(1024, 600), "Bananagrams", sf::Style::Titlebar);
	sf::View view = window.getDefaultView();
	view.setCenter(PPB / 2.0, PPB / 2.0);
	window.setView(view);

	int pos[2] = {0, 0};
	int delta[2] = {0, 0};
	float held[2] = {0, 0};

	float repeat_delay = 0.5;
	float repeat_speed = 0.1;

	sf::RectangleShape cursor(sf::Vector2f(PPB - DTHICK, PPB - DTHICK));
	cursor.setFillColor(sf::Color(0, 0, 0, 0));
	cursor.setOutlineThickness(THICK);
	cursor.setOutlineColor(sf::Color(0, 200, 0));

	sf::Clock clock;
	bool zoom_key = false;
	bool sprint_key = false;
	int last[2] = {0, 0};
	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed || (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape))
				window.close();
			else if (event.type == sf::Event::KeyPressed)
			{
				Tile* tile;
				switch (event.key.code)
				{
					case sf::Keyboard::Left:
						delta[0] = -1;
						break;
					case sf::Keyboard::Right:
						delta[0] = 1;
						break;
					case sf::Keyboard::Up:
						delta[1] = -1;
						break;
					case sf::Keyboard::Down:
						delta[1] = 1;
						break;
					case sf::Keyboard::LControl:
					case sf::Keyboard::RControl:
						zoom_key = true;
						break;
					case sf::Keyboard::LShift:
					case sf::Keyboard::RShift:
						sprint_key = true;
						break;
					case sf::Keyboard::BackSpace:
						tile = grid.remove(pos[0], pos[1]);
						if (tile != nullptr)
							tiles[tile->ch() - 'A'].push_back(tile);
						break;
					default:
						break;
				}
				if (sf::Keyboard::A <= event.key.code && event.key.code <= sf::Keyboard::Z)
				{
					if (tiles[event.key.code - sf::Keyboard::A].size() > 0)
					{
						Tile* tile = grid.swap(pos[0], pos[1], tiles[event.key.code - sf::Keyboard::A].back());
						tiles[event.key.code - sf::Keyboard::A].pop_back();
						if (tile != nullptr)
							tiles[tile->ch() - 'A'].push_back(tile);
						int next[2] = {0, 0};
						if (pos[0] == last[0] + 1 && pos[1] == last[1])
							next[0] = 1;
						if (pos[0] == last[0] && pos[1] == last[1] + 1)
							next[1] = 1;
						last[0] = pos[0];
						last[1] = pos[1];
						pos[0] += next[0];
						pos[1] += next[1];
					}
				}
			}
			else if (event.type == sf::Event::KeyReleased)
			{
				switch (event.key.code)
				{
					case sf::Keyboard::Left:
					case sf::Keyboard::Right:
						delta[0] = 0;
						break;
					case sf::Keyboard::Up:
					case sf::Keyboard::Down:
						delta[1] = 0;
						break;
					case sf::Keyboard::LControl:
					case sf::Keyboard::RControl:
						zoom_key = false;
						break;
					case sf::Keyboard::LShift:
					case sf::Keyboard::RShift:
						sprint_key = false;
						break;
					default:
						break;
				}
			}
		}

		float time = clock.getElapsedTime().asSeconds();
		clock.restart();

		if (zoom_key)
		{
			view.zoom(1 + delta[1] * (sprint_key ? 2 : 1) * time);
		}
		else
		{
			for (unsigned int i = 0; i < 2; i++)
			{
				if (delta[i] == 0)
					held[i] = 0;
				else
				{
					if (held[i] == 0)
						pos[i] += delta[i] * (sprint_key ? 2 : 1);
					else
						while (held[i] > repeat_delay)
						{
							pos[i] += delta[i] * (sprint_key ? 2 : 1);
							held[i] -= repeat_speed;
						}
					held[i] += time;
				}
			}
		}

		auto center = view.getCenter();
		float max = time * 500.0 * (sprint_key ? 2 : 1);
		sf::Vector2f diff(pos[0] * PPB + PPB / 2.0 - center.x, pos[1] * PPB + PPB / 2.0 - center.y);
		float length = std::sqrt(diff.x * diff.x + diff.y * diff.y);
		if (length > max)
		{
			diff.x = (diff.x * max) / length;
			diff.y = (diff.y * max) / length;
		}
		view.move(diff.x, diff.y);
		// don't allow zooming past default
		auto size = view.getSize();
		// TODO bleh hardcoded size
		if (size.x < 1024 || size.y < 600)
			view.setSize(1024, 600);
		window.setView(view);

		cursor.setPosition(pos[0] * PPB + THICK, pos[1] * PPB + THICK);

		window.clear(background);
		grid.draw_on(window);
		window.draw(cursor);

		window.display();
	}

	// delete unused tiles
	for (char ch = 'A'; ch <= 'Z'; ch++)
		for (auto tile: tiles[ch - 'A'])
			delete tile;

	return 0;
}
<|endoftext|>


<commit_before>8c7e6f38-4b02-11e5-87dc-28cfe9171a43<commit_msg>fixed bug<commit_after>8c8d5097-4b02-11e5-a809-28cfe9171a43<|endoftext|>


<commit_before>97b95291-2747-11e6-9175-e0f84713e7b8<commit_msg>Initial commit.13<commit_after>97c6c8d1-2747-11e6-b122-e0f84713e7b8<|endoftext|>


<commit_before>210c6db0-ad5a-11e7-8458-ac87a332f658<commit_msg>Nope, didn't work, now it does<commit_after>219aae40-ad5a-11e7-936a-ac87a332f658<|endoftext|>


<commit_before><commit_msg>update ./gb -h desc for ./gb inject.<commit_after><|endoftext|>


<commit_before>d2007066-2747-11e6-b40a-e0f84713e7b8<commit_msg>Typical bobby<commit_after>d2249df5-2747-11e6-865b-e0f84713e7b8<|endoftext|>


<commit_before>#include <iostream>
#include <functional>
#include <map>
#include <memory>
#include <chrono>
#include <vector>
#include <stdint.h>
#include <complex>
#include <type_traits>
#include <fstream>

#include "util.hpp"
#include "gl-api.hpp"

constexpr const char basic_wireframe_vert[] = R"(#version 330
    layout(location = 0) in vec3 vertex;
    layout(location = 1) in vec3 normal;
    layout(location = 2) in vec3 color;
    out vec3 v_color;
    uniform mat4 u_mvp;
    void main()
    {
        gl_Position = u_mvp * vec4(vertex.xyz, 1);
        v_color = color;
    }
)";

constexpr const char basic_wireframe_frag[] = R"(#version 330
    in vec3 v_color;
    out vec4 f_color;

    void main()
    {
        f_color = vec4(v_color, 1);
    }
)";

//////////////////////////
//   Main Application   //
//////////////////////////

void draw_mesh(GlShader * shader, GlMesh * mesh, const linalg::aliases::float4x4 & viewProj, const linalg::aliases::float4x4 & model)
{
    linalg::aliases::float4x4 modelViewProjectionMatrix = mul(viewProj, model);
    shader->bind();
    shader->uniform("u_mvp", modelViewProjectionMatrix);
    mesh->draw_elements();
    shader->unbind();
}

void upload_mesh(const geometry_mesh & cpu, GlMesh * gpu)
{
    const std::vector<linalg::aliases::float3> & verts = reinterpret_cast<const std::vector<linalg::aliases::float3> &>(cpu.vertices);
    const std::vector<linalg::aliases::uint3> & tris = reinterpret_cast<const std::vector<linalg::aliases::uint3> &>(cpu.triangles);
    gpu->set_vertices(verts, GL_DYNAMIC_DRAW);
    gpu->set_attribute(0, 3, GL_FLOAT, GL_FALSE, sizeof(geometry_vertex), (GLvoid*) offsetof(geometry_vertex, position));
    gpu->set_attribute(1, 3, GL_FLOAT, GL_FALSE, sizeof(geometry_vertex), (GLvoid*) offsetof(geometry_vertex, normal));
    gpu->set_attribute(2, 3, GL_FLOAT, GL_FALSE, sizeof(geometry_vertex), (GLvoid*) offsetof(geometry_vertex, color));
    gpu->set_elements(tris, GL_DYNAMIC_DRAW);
}

const linalg::aliases::float4x4 identity4x4 = { { 1, 0, 0, 0 },{ 0, 1, 0, 0 },{ 0, 0, 1, 0 },{ 0, 0, 0, 1 } };

std::unique_ptr<Window> win;
std::unique_ptr<GlShader> wireframeShader;
std::unique_ptr<GlMesh> gizmoEditorMesh;

int main(int argc, char * argv[])
{
    bool ml = 0, mr = 0, bf = 0, bl = 0, bb = 0, br = 0;

    camera cam = {};
    cam.yfov = 1.0f;
    cam.near_clip = 0.01f;
    cam.far_clip = 32.0f;
    cam.position = { 0,1.5f,4 };

    try
    {
        win.reset(new Window(1280, 800, "gizmin-example"));
        glfwSwapInterval(1);
    }
    catch (const std::exception & e)
    {
        std::cout << "Caught GLFW window exception: " << e.what() << std::endl;
    }

    linalg::aliases::int2 windowSize = win->get_window_size();
    wireframeShader.reset(new GlShader(basic_wireframe_vert, basic_wireframe_frag));

    gizmoEditorMesh.reset(new GlMesh());

    interaction_state gis;
    gizmo_context gizmoEditor;

    gizmoEditor.render = [&](const geometry_mesh & r)
    {
        upload_mesh(r, gizmoEditorMesh.get());
        draw_mesh(wireframeShader.get(), gizmoEditorMesh.get(), cam.get_viewproj_matrix({ 0, 0, windowSize.x, windowSize.y }), identity4x4);
    };

    win->on_char = [&](int codepoint)
    {
        auto e = make_input_event(win->get_glfw_window_handle(), InputEvent::CHAR, win->get_cursor_pos(), 0);
        e.value[0] = codepoint;
        if (win->on_input) win->on_input(e);
    };

    win->on_key = [&](int key, int action, int mods)
    {
        auto e = make_input_event(win->get_glfw_window_handle(), InputEvent::KEY, win->get_cursor_pos(), action);
        e.value[0] = key;
        if (win->on_input) win->on_input(e);
    };

    win->on_mouse_button = [&](int button, int action, int mods)
    {
        auto e = make_input_event(win->get_glfw_window_handle(), InputEvent::MOUSE, win->get_cursor_pos(), action);
        e.value[0] = button;
        if (win->on_input) win->on_input(e);
    };

    win->on_cursor_pos = [&](linalg::aliases::float2 position)
    {
        auto e = make_input_event(win->get_glfw_window_handle(), InputEvent::CURSOR, position, 0);
        if (win->on_input) win->on_input(e);
    };

    minalg::float2 lastCursor;

    win->on_input = [&](const InputEvent & event)
    {
        if (event.type == InputEvent::KEY)
        {
            if (event.value[0] == GLFW_KEY_L) gis.hotkey_local = event.is_down();
            if (event.value[0] == GLFW_KEY_T) gis.hotkey_translate = event.is_down();
            if (event.value[0] == GLFW_KEY_R) gis.hotkey_rotate = event.is_down();
            if (event.value[0] == GLFW_KEY_S) gis.hotkey_scale = event.is_down();
            if (event.value[0] == GLFW_KEY_LEFT_CONTROL) gis.hotkey_ctrl = event.is_down();

            if (event.value[0] == GLFW_KEY_W) bf = event.is_down();
            if (event.value[0] == GLFW_KEY_A) bl = event.is_down();
            if (event.value[0] == GLFW_KEY_S) bb = event.is_down();
            if (event.value[0] == GLFW_KEY_D) br = event.is_down();

        }
        else if (event.type == InputEvent::MOUSE)
        {
            gis.mouse_left = event.is_down();

            if (event.value[0] == GLFW_MOUSE_BUTTON_LEFT) ml = event.is_down();
            if (event.value[0] == GLFW_MOUSE_BUTTON_RIGHT) mr = event.is_down();
        }
        else if (event.type == InputEvent::CURSOR)
        {
            gis.cursor = minalg::float2(event.cursor.x, event.cursor.y);

            auto deltaCursorMotion = gis.cursor - lastCursor;
            if (mr)
            {
                cam.yaw -= deltaCursorMotion.x * 0.01f;
                cam.pitch -= deltaCursorMotion.y * 0.01f;
            }

            lastCursor = minalg::float2(event.cursor.x, event.cursor.y);
        }
    };

    float3 gp = float3(0, 0, 0);
    float4 ori = float4(0, 0, 0, 1);
    float3 scale = float3(1, 1, 1);
    rigid_transform transform;

    auto t0 = std::chrono::high_resolution_clock::now();
    while (!win->should_close())
    {
        glfwPollEvents();

        auto t1 = std::chrono::high_resolution_clock::now();
        float timestep = std::chrono::duration<float>(t1 - t0).count();
        t0 = t1;

        if (mr)
        {
            const linalg::aliases::float4 orientation = cam.get_orientation();
            linalg::aliases::float3 move;
            if (bf) move -= qzdir(orientation);
            if (bl) move -= qxdir(orientation);
            if (bb) move += qzdir(orientation);
            if (br) move += qxdir(orientation);
            if (length2(move) > 0) cam.position += normalize(move) * (timestep * 10);
        }

        glViewport(0, 0, windowSize.x, windowSize.y);

        glEnable(GL_CULL_FACE);
        glEnable(GL_DEPTH_TEST);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);

        linalg::aliases::float4 cameraOrientation = cam.get_orientation();

        // Gizmo input interaction state populated via win->on_input(...) callback above.
        // Now populate other app parameters:
        gis.viewport = rect{0, 0, windowSize.x, windowSize.y};
        gis.timestep = timestep;
        gis.cam.near_clip = cam.near_clip;
        gis.cam.far_clip = cam.far_clip;
        gis.cam.yfov = cam.yfov;
        gis.cam.position = minalg::float3(cam.position.x, cam.position.y, cam.position.z);
        gis.cam.orientation = minalg::float4(cameraOrientation.x, cameraOrientation.y, cameraOrientation.z, cameraOrientation.w);

        gizmoEditor.update(gis);

        //position_gizmo("position-example-gizmo", gizmoEditor, gp);
        //orientation_gizmo("orientation-example-gizmo", gizmoEditor, gp, ori);
        //scale_gizmo("scale-example-gizmo", gizmoEditor, gp, scale);

        transform_gizmo("xform-example-gizmo", gizmoEditor, transform);

        //std::cout << "position: " << transform.position << std::endl;
        //std::cout << "local: " << gizmoEditor.local_toggle << std::endl;
        std::cout << "orientation: " << transform.orientation << std::endl;

        gizmoEditor.draw();

        gl_check_error(__FILE__, __LINE__);

        win->swap_buffers();
    }
    return EXIT_SUCCESS;
}
<commit_msg>cleanup example a bit<commit_after>#include <iostream>
#include <functional>
#include <map>
#include <memory>
#include <chrono>
#include <vector>
#include <stdint.h>
#include <complex>
#include <type_traits>
#include <fstream>

#include "util.hpp"
#include "gl-api.hpp"

constexpr const char basic_wireframe_vert[] = R"(#version 330
    layout(location = 0) in vec3 vertex;
    layout(location = 1) in vec3 normal;
    layout(location = 2) in vec3 color;
    out vec3 v_color;
    uniform mat4 u_mvp;
    void main()
    {
        gl_Position = u_mvp * vec4(vertex.xyz, 1);
        v_color = color;
    }
)";

constexpr const char basic_wireframe_frag[] = R"(#version 330
    in vec3 v_color;
    out vec4 f_color;

    void main()
    {
        f_color = vec4(v_color, 1);
    }
)";

//////////////////////////
//   Main Application   //
//////////////////////////

void draw_mesh(GlShader * shader, GlMesh * mesh, const linalg::aliases::float4x4 & viewProj, const linalg::aliases::float4x4 & model)
{
    linalg::aliases::float4x4 modelViewProjectionMatrix = mul(viewProj, model);
    shader->bind();
    shader->uniform("u_mvp", modelViewProjectionMatrix);
    mesh->draw_elements();
    shader->unbind();
}

void upload_mesh(const geometry_mesh & cpu, GlMesh * gpu)
{
    const std::vector<linalg::aliases::float3> & verts = reinterpret_cast<const std::vector<linalg::aliases::float3> &>(cpu.vertices);
    const std::vector<linalg::aliases::uint3> & tris = reinterpret_cast<const std::vector<linalg::aliases::uint3> &>(cpu.triangles);
    gpu->set_vertices(verts, GL_DYNAMIC_DRAW);
    gpu->set_attribute(0, 3, GL_FLOAT, GL_FALSE, sizeof(geometry_vertex), (GLvoid*) offsetof(geometry_vertex, position));
    gpu->set_attribute(1, 3, GL_FLOAT, GL_FALSE, sizeof(geometry_vertex), (GLvoid*) offsetof(geometry_vertex, normal));
    gpu->set_attribute(2, 3, GL_FLOAT, GL_FALSE, sizeof(geometry_vertex), (GLvoid*) offsetof(geometry_vertex, color));
    gpu->set_elements(tris, GL_DYNAMIC_DRAW);
}

const linalg::aliases::float4x4 identity4x4 = { { 1, 0, 0, 0 },{ 0, 1, 0, 0 },{ 0, 0, 1, 0 },{ 0, 0, 0, 1 } };

std::unique_ptr<Window> win;
std::unique_ptr<GlShader> wireframeShader;
std::unique_ptr<GlMesh> gizmoEditorMesh;

int main(int argc, char * argv[])
{
    bool ml = 0, mr = 0, bf = 0, bl = 0, bb = 0, br = 0;

    camera cam = {};
    cam.yfov = 1.0f;
    cam.near_clip = 0.01f;
    cam.far_clip = 32.0f;
    cam.position = { 0,1.5f,4 };

    try
    {
        win.reset(new Window(1280, 800, "gizmin-example"));
        glfwSwapInterval(1);
    }
    catch (const std::exception & e)
    {
        std::cout << "Caught GLFW window exception: " << e.what() << std::endl;
    }

    linalg::aliases::int2 windowSize = win->get_window_size();
    wireframeShader.reset(new GlShader(basic_wireframe_vert, basic_wireframe_frag));

    gizmoEditorMesh.reset(new GlMesh());

    interaction_state gis;
    gizmo_context gizmoEditor;

    gizmoEditor.render = [&](const geometry_mesh & r)
    {
        upload_mesh(r, gizmoEditorMesh.get());
        draw_mesh(wireframeShader.get(), gizmoEditorMesh.get(), cam.get_viewproj_matrix({ 0, 0, windowSize.x, windowSize.y }), identity4x4);
    };

    win->on_char = [&](int codepoint)
    {
        auto e = make_input_event(win->get_glfw_window_handle(), InputEvent::CHAR, win->get_cursor_pos(), 0);
        e.value[0] = codepoint;
        if (win->on_input) win->on_input(e);
    };

    win->on_key = [&](int key, int action, int mods)
    {
        auto e = make_input_event(win->get_glfw_window_handle(), InputEvent::KEY, win->get_cursor_pos(), action);
        e.value[0] = key;
        if (win->on_input) win->on_input(e);
    };

    win->on_mouse_button = [&](int button, int action, int mods)
    {
        auto e = make_input_event(win->get_glfw_window_handle(), InputEvent::MOUSE, win->get_cursor_pos(), action);
        e.value[0] = button;
        if (win->on_input) win->on_input(e);
    };

    win->on_cursor_pos = [&](linalg::aliases::float2 position)
    {
        auto e = make_input_event(win->get_glfw_window_handle(), InputEvent::CURSOR, position, 0);
        if (win->on_input) win->on_input(e);
    };

    minalg::float2 lastCursor;

    win->on_input = [&](const InputEvent & event)
    {
        if (event.type == InputEvent::KEY)
        {
            if (event.value[0] == GLFW_KEY_L) gis.hotkey_local = event.is_down();
            if (event.value[0] == GLFW_KEY_T) gis.hotkey_translate = event.is_down();
            if (event.value[0] == GLFW_KEY_R) gis.hotkey_rotate = event.is_down();
            if (event.value[0] == GLFW_KEY_S) gis.hotkey_scale = event.is_down();
            if (event.value[0] == GLFW_KEY_LEFT_CONTROL) gis.hotkey_ctrl = event.is_down();

            if (event.value[0] == GLFW_KEY_W) bf = event.is_down();
            if (event.value[0] == GLFW_KEY_A) bl = event.is_down();
            if (event.value[0] == GLFW_KEY_S) bb = event.is_down();
            if (event.value[0] == GLFW_KEY_D) br = event.is_down();

        }
        else if (event.type == InputEvent::MOUSE)
        {
            gis.mouse_left = event.is_down();

            if (event.value[0] == GLFW_MOUSE_BUTTON_LEFT) ml = event.is_down();
            if (event.value[0] == GLFW_MOUSE_BUTTON_RIGHT) mr = event.is_down();
        }
        else if (event.type == InputEvent::CURSOR)
        {
            gis.cursor = minalg::float2(event.cursor.x, event.cursor.y);

            auto deltaCursorMotion = gis.cursor - lastCursor;
            if (mr)
            {
                cam.yaw -= deltaCursorMotion.x * 0.01f;
                cam.pitch -= deltaCursorMotion.y * 0.01f;
            }

            lastCursor = minalg::float2(event.cursor.x, event.cursor.y);
        }
    };

    rigid_transform transform;

    auto t0 = std::chrono::high_resolution_clock::now();
    while (!win->should_close())
    {
        glfwPollEvents();

        auto t1 = std::chrono::high_resolution_clock::now();
        float timestep = std::chrono::duration<float>(t1 - t0).count();
        t0 = t1;

        if (mr)
        {
            const linalg::aliases::float4 orientation = cam.get_orientation();
            linalg::aliases::float3 move;
            if (bf) move -= qzdir(orientation);
            if (bl) move -= qxdir(orientation);
            if (bb) move += qzdir(orientation);
            if (br) move += qxdir(orientation);
            if (length2(move) > 0) cam.position += normalize(move) * (timestep * 10);
        }

        glViewport(0, 0, windowSize.x, windowSize.y);

        glEnable(GL_CULL_FACE);
        glEnable(GL_DEPTH_TEST);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);

        linalg::aliases::float4 cameraOrientation = cam.get_orientation();

        // Gizmo input interaction state populated via win->on_input(...) callback above.
        // Now populate other app parameters:
        gis.viewport = rect{0, 0, windowSize.x, windowSize.y};
        gis.timestep = timestep;
        gis.cam.near_clip = cam.near_clip;
        gis.cam.far_clip = cam.far_clip;
        gis.cam.yfov = cam.yfov;
        gis.cam.position = minalg::float3(cam.position.x, cam.position.y, cam.position.z);
        gis.cam.orientation = minalg::float4(cameraOrientation.x, cameraOrientation.y, cameraOrientation.z, cameraOrientation.w);

        gizmoEditor.update(gis);
        transform_gizmo("xform-example-gizmo", gizmoEditor, transform);
        gizmoEditor.draw();

        gl_check_error(__FILE__, __LINE__);

        win->swap_buffers();
    }
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>cea05e2b-2747-11e6-bc37-e0f84713e7b8<commit_msg>Too poor for Dropbox<commit_after>cecd65d1-2747-11e6-84b2-e0f84713e7b8<|endoftext|>


<commit_before>#include "spbits.h"
#include <ap_int.h>
#include "primitive.h"
#include <fstream>
#include <iostream>

using namespace std;

void primitive11::top_prim_conv11(
			ap_uint<seg_ch> vpf,
			ap_uint<4> quality[seg_ch],
			ap_uint<bw_wg> wiregroup[seg_ch],
			ap_uint<bw_hs> hstrip[seg_ch],
			ap_uint<4> clctpat[seg_ch],
			ap_uint<8> station,
			ap_uint<8> cscid,
			ap_uint<13> r_in,
			ap_uint<1> we,
			ap_uint<bw_fph> ph[seg_ch],
			ap_uint<bw_th> th[seg_ch*seg_ch],
			ap_uint<seg_ch> *vl,
			ap_uint<3> *phzvl,
			ap_uint<seg_ch> *me11a,
			ap_uint<4> clctpat_r[seg_ch],
			ap_uint<ph_hit_w> *ph_hit,
			ap_uint<th_hit_w> *th_hit,
			ap_uint<2>  sel,
			ap_uint<bw_addr>  addr,
			ap_uint<1> endcap,
			ap_uint<12> *r_out)
{
#pragma HLS LATENCY max=0
#pragma HLS INTERFACE ap_ctrl_none port=return
#pragma HLS INLINE off
#pragma HLS PIPELINE II=1

	ap_uint<3> a_phzvl;
	ap_uint<ph_hit_w> a_ph_hit;
	ap_uint<th_hit_w> a_th_hit;

if(we==1)
{
#pragma HLS PROTOCOL fixed
	this->mem11(r_in,
			 we,
			 addr,
			 sel,
			 station,
			 cscid,
			 endcap
			 );

}

else
{
#pragma HLS PROTOCOL fixed
	this->prim_conv11(
					vpf, quality, wiregroup, hstrip,
			 		clctpat, station, cscid,
			 		ph,	th,	vl,	&a_phzvl,me11a, clctpat_r,
			 	    &a_ph_hit, &a_th_hit, sel, addr,
			 	    endcap,r_out
			 		);

}

*phzvl=a_phzvl;
*ph_hit=a_ph_hit;
*th_hit=a_th_hit;
}

<commit_msg>Delete top_prim_conv11.cpp<commit_after><|endoftext|>


<commit_before>78d860d1-ad5b-11e7-82b0-ac87a332f658<commit_msg>oh my, I hate roselyn<commit_after>79578738-ad5b-11e7-a1fb-ac87a332f658<|endoftext|>


<commit_before>3253b8b3-ad5a-11e7-846c-ac87a332f658<commit_msg>Now it no longer crashes if X<commit_after>32df2f4f-ad5a-11e7-a754-ac87a332f658<|endoftext|>


<commit_before>#include "api.hpp"
#include "system.hpp"
#include "threadpool.hpp"
#include "command.hpp"

#include "string.h"
#include <string>
#include <iostream>
#include <cstdlib>

using namespace std;

const char * usage = R"EOS(    Usage:
        %1$s [-v] [-q] [-n nthreads] [--] <command> <arguments...>

            -v              run verbose
            -q              run quiet
            -n nthreads     use nthreads threads
            --              end option parsing

    Placeholders:
        You can use {} or {i} with i a non-negative integer to refer
        to placeholders:
            - ls {}
            - cat {1} {0}
        BASH-style replacements are supported:
            - cat {} > {0/e/o}      # replace the first 'e' with 'o'
            - cat {} > {0//e/o}     # replace all 'e' with 'o'
            - cat {} > {0/%%e/o}     # replace the final character
                                    # with 'o' if it is 'e'

    Example usage:
        The current directory contains story1, story1.part2, story2 and story2.part2.
        Running the following command will result in the files *.part2 being appended
        to the other files and being removed:
                %1$s 'cat {} >> {} && rm {0}' '*.part2' 'story{1,2}'

        The current directory contains story1.part1, story1.part2, story2.part1 and
        story2.part2. To create files story1 and story2 containing the entire stories:
                %1$s 'cat {} {0/%%1/2} > {0/%%.part1/}' \*.part1
)EOS";

char *command;
void PrintUsage() {
    fprintf(stderr, usage, command);
}

bool matchesNoArg(const char *str, const char *pattern) {
    return !strcmp(str, pattern);
}

bool matchesWithArg(const char *str, const char *pattern, const char **begin, int &index) {
    if (!strcmp(str, pattern))
        return true;

    size_t len = strlen(pattern);
    for (size_t i = 0; i < len; i++) {
        if (str[i] != pattern[i])
            return false;
    }

    *begin = str + len;
    if (**begin == '=')
        (*begin)++;

    index++;
    return true;
}

int main(int argc, char **argv) {
    command = argv[0];

    if (argc == 1) {
        PrintUsage();
        return -1;
    }

    uint nbThreads = worker::System::getNbCores();

    int argpos = 1;
    for (; argpos < argc; argpos++) {
        const char *curr = argv[argpos];
        const char *next = (argpos == argc - 1) ? NULL : argv[argpos+1];
        if (matchesWithArg(curr, "-n", &next, argpos) || matchesWithArg(curr, "--nthreads", &next, argpos)) {
            if (next == NULL) {
                PrintUsage();
                worker::Fatal("No argument given for \"-n\"");
            }
            int _nbThreads = atoi(next);
            if (_nbThreads < 0) {
                worker::Fatal("Number of threads must be positive, not %d", _nbThreads);
            }
            nbThreads = static_cast<uint>(_nbThreads);
        } else
        if (matchesNoArg(curr, "-h") || matchesNoArg(curr, "--help")) {
            PrintUsage();
            return 1;
        } else
        if (matchesNoArg(curr, "-q") || matchesNoArg(curr, "--quiet")) {
            worker::quiet = true;
            worker::verbose = false;
        } else
        if (matchesNoArg(curr, "-v") || matchesNoArg(curr, "--verbose")) {
            worker::quiet = false;
            worker::verbose = true;
        } else
        if (matchesNoArg(curr, "--")) {
            argpos++;
            break;
        } else
            break;
    }

    worker::Command command(argv[argpos]);
    const uint nbPlaceholders = command.getNbPlaceholders();
    argpos++;

    worker::Debug("Parsed command with %u placeholders", nbPlaceholders);

    if (nbPlaceholders != static_cast<uint>(argc - argpos)) {
        worker::Fatal("Invalid number of arguments given, expected %d placeholder arguments but got %d", nbPlaceholders, argc - argpos);
    }

    vector<string> *jobArguments = new vector<string>[nbPlaceholders];

    for (uint idx = 0; argpos < argc; argpos++, idx++) {
        jobArguments[idx] = worker::parseGlob(argv[argpos]);
    }

    if (nbPlaceholders > 0) {
        uint nbJobs = jobArguments[0].size();
        for (uint i = 1; i < nbPlaceholders; i++) {
            if (jobArguments[i].size() != nbJobs) {
                worker::Fatal("Placeholder %u matches %u items while placeholder 0 matches %u items!", i, jobArguments[i].size(), nbJobs);
            }
        }
    }

    uint nbJobs = (nbPlaceholders == 0) ? 1 : jobArguments[0].size();
    worker::Debug("Using %u jobs", nbJobs);

    worker::ThreadPool threadPool(min(nbThreads, nbJobs));

    for (uint i = 0; i < nbJobs; i++) {
        vector<string> thisArgs;

        for (uint j = 0; j < nbPlaceholders; j++)
            thisArgs.push_back(jobArguments[j][i]);

        threadPool.schedule(command.fillArguments(thisArgs));
    }

    delete[] jobArguments;

    threadPool.join();
}<commit_msg>switched from <iostream> to <cstdio><commit_after>#include "api.hpp"
#include "system.hpp"
#include "threadpool.hpp"
#include "command.hpp"

#include "string.h"
#include <string>
#include <cstdio>
#include <cstdlib>

using namespace std;

const char * usage = R"EOS(    Usage:
        %1$s [-v] [-q] [-n nthreads] [--] <command> <arguments...>

            -v              run verbose
            -q              run quiet
            -n nthreads     use nthreads threads
            --              end option parsing

    Placeholders:
        You can use {} or {i} with i a non-negative integer to refer
        to placeholders:
            - ls {}
            - cat {1} {0}
        BASH-style replacements are supported:
            - cat {} > {0/e/o}      # replace the first 'e' with 'o'
            - cat {} > {0//e/o}     # replace all 'e' with 'o'
            - cat {} > {0/%%e/o}     # replace the final character
                                    # with 'o' if it is 'e'

    Example usage:
        The current directory contains story1, story1.part2, story2 and story2.part2.
        Running the following command will result in the files *.part2 being appended
        to the other files and being removed:
                %1$s 'cat {} >> {} && rm {0}' '*.part2' 'story{1,2}'

        The current directory contains story1.part1, story1.part2, story2.part1 and
        story2.part2. To create files story1 and story2 containing the entire stories:
                %1$s 'cat {} {0/%%1/2} > {0/%%.part1/}' \*.part1
)EOS";

char *command;
void PrintUsage() {
    fprintf(stderr, usage, command);
}

bool matchesNoArg(const char *str, const char *pattern) {
    return !strcmp(str, pattern);
}

bool matchesWithArg(const char *str, const char *pattern, const char **begin, int &index) {
    if (!strcmp(str, pattern))
        return true;

    size_t len = strlen(pattern);
    for (size_t i = 0; i < len; i++) {
        if (str[i] != pattern[i])
            return false;
    }

    *begin = str + len;
    if (**begin == '=')
        (*begin)++;

    index++;
    return true;
}

int main(int argc, char **argv) {
    command = argv[0];

    if (argc == 1) {
        PrintUsage();
        return -1;
    }

    uint nbThreads = worker::System::getNbCores();

    int argpos = 1;
    for (; argpos < argc; argpos++) {
        const char *curr = argv[argpos];
        const char *next = (argpos == argc - 1) ? NULL : argv[argpos+1];
        if (matchesWithArg(curr, "-n", &next, argpos) || matchesWithArg(curr, "--nthreads", &next, argpos)) {
            if (next == NULL) {
                PrintUsage();
                worker::Fatal("No argument given for \"-n\"");
            }
            int _nbThreads = atoi(next);
            if (_nbThreads < 0) {
                worker::Fatal("Number of threads must be positive, not %d", _nbThreads);
            }
            nbThreads = static_cast<uint>(_nbThreads);
        } else
        if (matchesNoArg(curr, "-h") || matchesNoArg(curr, "--help")) {
            PrintUsage();
            return 1;
        } else
        if (matchesNoArg(curr, "-q") || matchesNoArg(curr, "--quiet")) {
            worker::quiet = true;
            worker::verbose = false;
        } else
        if (matchesNoArg(curr, "-v") || matchesNoArg(curr, "--verbose")) {
            worker::quiet = false;
            worker::verbose = true;
        } else
        if (matchesNoArg(curr, "--")) {
            argpos++;
            break;
        } else
            break;
    }

    worker::Command command(argv[argpos]);
    const uint nbPlaceholders = command.getNbPlaceholders();
    argpos++;

    worker::Debug("Parsed command with %u placeholders", nbPlaceholders);

    if (nbPlaceholders != static_cast<uint>(argc - argpos)) {
        worker::Fatal("Invalid number of arguments given, expected %d placeholder arguments but got %d", nbPlaceholders, argc - argpos);
    }

    vector<string> *jobArguments = new vector<string>[nbPlaceholders];

    for (uint idx = 0; argpos < argc; argpos++, idx++) {
        jobArguments[idx] = worker::parseGlob(argv[argpos]);
    }

    if (nbPlaceholders > 0) {
        uint nbJobs = jobArguments[0].size();
        for (uint i = 1; i < nbPlaceholders; i++) {
            if (jobArguments[i].size() != nbJobs) {
                worker::Fatal("Placeholder %u matches %u items while placeholder 0 matches %u items!", i, jobArguments[i].size(), nbJobs);
            }
        }
    }

    uint nbJobs = (nbPlaceholders == 0) ? 1 : jobArguments[0].size();
    worker::Debug("Using %u jobs", nbJobs);

    worker::ThreadPool threadPool(min(nbThreads, nbJobs));

    for (uint i = 0; i < nbJobs; i++) {
        vector<string> thisArgs;

        for (uint j = 0; j < nbPlaceholders; j++)
            thisArgs.push_back(jobArguments[j][i]);

        threadPool.schedule(command.fillArguments(thisArgs));
    }

    delete[] jobArguments;

    threadPool.join();
}<|endoftext|>


<commit_before>#include <GL/glew.h> // glew must be included before the main gl libs
#include <GL/glut.h> // doing otherwise causes compiler shouting
#include <iostream>
#include <chrono>

#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp> //Makes passing matrices to shaders easier

#include "ShaderLoader.h"

//--Data types
//This object will define the attributes of a vertex(position, color, etc...)
struct Vertex
{
    GLfloat position[3];
    GLfloat color[3];
};

//--Evil Global variables
//Just for this example!
int w = 640, h = 480;// Window size
GLuint program;// The GLSL program handle
GLuint vbo_geometry;// VBO handle for our geometry

//uniform locations
GLint loc_mvpmat;// Location of the modelviewprojection matrix in the shader

//attribute locations
GLint loc_position;
GLint loc_color;

//transform matrices
glm::mat4 model;//obj->world each object should have its own model matrix
glm::mat4 view;//world->eye
glm::mat4 projection;//eye->clip
glm::mat4 mvp;//premultiplied modelviewprojection

//Evil Global Variables
bool exit_flag = false;
bool clockwise;
bool spinning;
GLint optionsMenu;

//--GLUT Callbacks
void render();
void update();
void reshape(int n_w, int n_h);
void keyboard(unsigned char key, int x_pos, int y_pos);
void mouse(int button, int state, int x, int y);
void menu(int index);

//--Resource management
bool initialize();
void cleanUp();

//--Random time things
float getDT();
std::chrono::time_point<std::chrono::high_resolution_clock> t1,t2;

//--Main
int main(int argc, char **argv)
{
    // Initialize glut
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowSize(w, h);
    // Name and create the Window
    glutCreateWindow("Interaction Example");

    // Now that the window is created the GL context is fully set up
    // Because of that we can now initialize GLEW to prepare work with shaders
    GLenum status = glewInit();
    if( status != GLEW_OK)
    {
        std::cerr << "[F] GLEW NOT INITIALIZED: ";
        std::cerr << glewGetErrorString(status) << std::endl;
        return -1;
    }

    // Set all of the callbacks to GLUT that we need
    glutDisplayFunc(render);// Called when its time to display
    glutReshapeFunc(reshape);// Called if the window is resized
    glutIdleFunc(update);// Called if there is nothing else to do
    glutKeyboardFunc(keyboard);// Called if there is keyboard input
    glutMouseFunc(mouse);//Called if there is mouse input

    optionsMenu = glutCreateMenu(menu);
    glutAddMenuEntry("Rotate", 1);
    glutAddMenuEntry("Exit Program", 2);
    glutAttachMenu(GLUT_RIGHT_BUTTON);

    // Initialize all of our resources(shaders, geometry)
    bool init = initialize();
    if(init)
    {
        t1 = std::chrono::high_resolution_clock::now();
        glutMainLoop();
    }

    // Clean up after ourselves
    cleanUp();
    return 0;
}

//--Implementations
void render()
{
    //--Render the scene

    //clear the screen
    glClearColor(0.0, 0.0, 0.2, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //premultiply the matrix for this example
    mvp = projection * view * model;

    //enable the shader program
    glUseProgram(program);

    //upload the matrix to the shader
    glUniformMatrix4fv(loc_mvpmat, 1, GL_FALSE, glm::value_ptr(mvp));

    //set up the Vertex Buffer Object so it can be drawn
    glEnableVertexAttribArray(loc_position);
    glEnableVertexAttribArray(loc_color);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_geometry);
    //set pointers into the vbo for each of the attributes(position and color)
    glVertexAttribPointer( loc_position,//location of attribute
                           3,//number of elements
                           GL_FLOAT,//type
                           GL_FALSE,//normalized?
                           sizeof(Vertex),//stride
                           0);//offset

    glVertexAttribPointer( loc_color,
                           3,
                           GL_FLOAT,
                           GL_FALSE,
                           sizeof(Vertex),
                           (void*)offsetof(Vertex,color));

    glDrawArrays(GL_TRIANGLES, 0, 36);//mode, starting index, count

    //clean up
    glDisableVertexAttribArray(loc_position);
    glDisableVertexAttribArray(loc_color);

    //swap the buffers
    glutSwapBuffers();
}

void update()
{
    //total time
    static float angle = 0.0;
    static float rotation = 0.0;
    float dt = getDT();// if you have anything moving, use dt.

    angle += dt * M_PI/2; //move through 90 degrees a second
    model = glm::translate( glm::mat4(1.0f), glm::vec3(4.0 * sin(angle), 0.0, 4.0 * cos(angle)));
    if(clockwise)
    {
        if(spinning)
            rotation -= .01;
        model = glm::rotate( model, rotation, glm::vec3(0, 1, 0) );
    }
    else
    {
        if(spinning)
            rotation += .01;
        model = glm::rotate( model, rotation, glm::vec3(0, 1, 0) );
    }
    // Update the state of the scene
    glutPostRedisplay();//call the display callback

    if(exit_flag)
    {
      glutDestroyMenu(optionsMenu);
      exit(0);
    }
}

void reshape(int n_w, int n_h)
{
    w = n_w;
    h = n_h;
    //Change the viewport to be correct
    glViewport( 0, 0, w, h);
    //Update the projection matrix as well
    //See the init function for an explaination
    projection = glm::perspective(45.0f, float(w)/float(h), 0.01f, 100.0f);

}

void keyboard(unsigned char key, int x_pos, int y_pos)
{
    switch (key)
    {
      case 27:  //ESC
        exit_flag = true;
        break;
      case 97:  //'a'
      case 65:  //'A'
        clockwise = false;
        break;
      case 100: //'d'
      case 68:  //'D'
        clockwise = true;
        break;
      default:  //Default
        break;
    }
}

void mouse(int button, int state, int x, int y)
{
  if(state == GLUT_UP)
  {
    switch(button)
    {
      case GLUT_LEFT_BUTTON:
        clockwise = !clockwise;
        break;
      default:
        break;
    }
  }
}

void menu(int index)
{
  //std::cout << index << std::endl;
  switch(index)
  {
    case 1: //Rotate
        spinning = !spinning;
      break;
    case 2: //Exit Program
        exit_flag = true;
      break;
    }
}

bool initialize()
{
    // Initialize basic geometry and shaders for this example

    //this defines a cube, this is why a model loader is nice
    //you can also do this with a draw elements and indices, try to get that working
    Vertex geometry[] = { {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
                          {{-1.0, -1.0, 1.0}, {0.0, 0.0, 1.0}},
                          {{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},

                          {{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},
                          {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
                          {{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},

                          {{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},
                          {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
                          {{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},

                          {{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},
                          {{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},
                          {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},

                          {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
                          {{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},
                          {{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},

                          {{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},
                          {{-1.0, -1.0, 1.0}, {0.0, 0.0, 1.0}},
                          {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},

                          {{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},
                          {{-1.0, -1.0, 1.0}, {0.0, 0.0, 1.0}},
                          {{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},

                          {{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
                          {{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},
                          {{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},

                          {{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},
                          {{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
                          {{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},

                          {{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
                          {{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},
                          {{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},

                          {{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
                          {{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},
                          {{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},

                          {{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
                          {{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},
                          {{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}}
                        };
    // Create a Vertex Buffer object to store this vertex info on the GPU
    glGenBuffers(1, &vbo_geometry);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_geometry);
    glBufferData(GL_ARRAY_BUFFER, sizeof(geometry), geometry, GL_STATIC_DRAW);

    //--Geometry done

    ShaderLoader shaderLoader = ShaderLoader(
        "defaultVertexShader.vs", "defaultFragmentShader.fs");
    program = shaderLoader.loadShader();
    glUseProgram(program);

    //Now we set the locations of the attributes and uniforms
    //this allows us to access them easily while rendering
    loc_position = glGetAttribLocation(program,
                    const_cast<const char*>("v_position"));
    if(loc_position == -1)
    {
        std::cerr << "[F] POSITION NOT FOUND" << std::endl;
        return false;
    }

    loc_color = glGetAttribLocation(program,
                    const_cast<const char*>("v_color"));
    if(loc_color == -1)
    {
        std::cerr << "[F] V_COLOR NOT FOUND" << std::endl;
        return false;
    }

    loc_mvpmat = glGetUniformLocation(program,
                    const_cast<const char*>("mvpMatrix"));
    if(loc_mvpmat == -1)
    {
        std::cerr << "[F] MVPMATRIX NOT FOUND" << std::endl;
        return false;
    }

    //--Init the view and projection matrices
    //  if you will be having a moving camera the view matrix will need to more dynamic
    //  ...Like you should update it before you render more dynamic
    //  for this project having them static will be fine
    view = glm::lookAt( glm::vec3(0.0, 8.0, -16.0), //Eye Position
                        glm::vec3(0.0, 0.0, 0.0), //Focus point
                        glm::vec3(0.0, 1.0, 0.0)); //Positive Y is up

    projection = glm::perspective( 45.0f, //the FoV typically 90 degrees is good which is what this is set to
                                   float(w)/float(h), //Aspect Ratio, so Circles stay Circular
                                   0.01f, //Distance to the near plane, normally a small value like this
                                   100.0f); //Distance to the far plane,

    //enable depth testing
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    //and its done
    return true;
}

void cleanUp()
{
    // Clean up, Clean up
    glDeleteProgram(program);
    glDeleteBuffers(1, &vbo_geometry);
}

//returns the time delta
float getDT()
{
    float ret;
    t2 = std::chrono::high_resolution_clock::now();
    ret = std::chrono::duration_cast< std::chrono::duration<float> >(t2-t1).count();
    t1 = std::chrono::high_resolution_clock::now();
    return ret;
}<commit_msg>fixed rotation speed on ubuntu 14.04<commit_after>#include <GL/glew.h> // glew must be included before the main gl libs
#include <GL/glut.h> // doing otherwise causes compiler shouting
#include <iostream>
#include <chrono>

#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp> //Makes passing matrices to shaders easier

#include "ShaderLoader.h"

//--Data types
//This object will define the attributes of a vertex(position, color, etc...)
struct Vertex
{
    GLfloat position[3];
    GLfloat color[3];
};

//--Evil Global variables
//Just for this example!
int w = 640, h = 480;// Window size
GLuint program;// The GLSL program handle
GLuint vbo_geometry;// VBO handle for our geometry

//uniform locations
GLint loc_mvpmat;// Location of the modelviewprojection matrix in the shader

//attribute locations
GLint loc_position;
GLint loc_color;

//transform matrices
glm::mat4 model;//obj->world each object should have its own model matrix
glm::mat4 view;//world->eye
glm::mat4 projection;//eye->clip
glm::mat4 mvp;//premultiplied modelviewprojection

//Evil Global Variables
bool exit_flag = false;
bool clockwise;
bool spinning;
GLint optionsMenu;

//--GLUT Callbacks
void render();
void update();
void reshape(int n_w, int n_h);
void keyboard(unsigned char key, int x_pos, int y_pos);
void mouse(int button, int state, int x, int y);
void menu(int index);

//--Resource management
bool initialize();
void cleanUp();

//--Random time things
float getDT();
std::chrono::time_point<std::chrono::high_resolution_clock> t1,t2;

//--Main
int main(int argc, char **argv)
{
    // Initialize glut
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowSize(w, h);
    // Name and create the Window
    glutCreateWindow("Interaction Example");

    // Now that the window is created the GL context is fully set up
    // Because of that we can now initialize GLEW to prepare work with shaders
    GLenum status = glewInit();
    if( status != GLEW_OK)
    {
        std::cerr << "[F] GLEW NOT INITIALIZED: ";
        std::cerr << glewGetErrorString(status) << std::endl;
        return -1;
    }

    // Set all of the callbacks to GLUT that we need
    glutDisplayFunc(render);// Called when its time to display
    glutReshapeFunc(reshape);// Called if the window is resized
    glutIdleFunc(update);// Called if there is nothing else to do
    glutKeyboardFunc(keyboard);// Called if there is keyboard input
    glutMouseFunc(mouse);//Called if there is mouse input

    optionsMenu = glutCreateMenu(menu);
    glutAddMenuEntry("Rotate", 1);
    glutAddMenuEntry("Exit Program", 2);
    glutAttachMenu(GLUT_RIGHT_BUTTON);

    // Initialize all of our resources(shaders, geometry)
    bool init = initialize();
    if(init)
    {
        t1 = std::chrono::high_resolution_clock::now();
        glutMainLoop();
    }

    // Clean up after ourselves
    cleanUp();
    return 0;
}

//--Implementations
void render()
{
    //--Render the scene

    //clear the screen
    glClearColor(0.0, 0.0, 0.2, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //premultiply the matrix for this example
    mvp = projection * view * model;

    //enable the shader program
    glUseProgram(program);

    //upload the matrix to the shader
    glUniformMatrix4fv(loc_mvpmat, 1, GL_FALSE, glm::value_ptr(mvp));

    //set up the Vertex Buffer Object so it can be drawn
    glEnableVertexAttribArray(loc_position);
    glEnableVertexAttribArray(loc_color);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_geometry);
    //set pointers into the vbo for each of the attributes(position and color)
    glVertexAttribPointer( loc_position,//location of attribute
                           3,//number of elements
                           GL_FLOAT,//type
                           GL_FALSE,//normalized?
                           sizeof(Vertex),//stride
                           0);//offset

    glVertexAttribPointer( loc_color,
                           3,
                           GL_FLOAT,
                           GL_FALSE,
                           sizeof(Vertex),
                           (void*)offsetof(Vertex,color));

    glDrawArrays(GL_TRIANGLES, 0, 36);//mode, starting index, count

    //clean up
    glDisableVertexAttribArray(loc_position);
    glDisableVertexAttribArray(loc_color);

    //swap the buffers
    glutSwapBuffers();
}

void update()
{
    //total time
    static float angle = 0.0;
    static float rotation = 0.0;
    float dt = getDT();// if you have anything moving, use dt.

    angle += dt * M_PI/2; //move through 90 degrees a second
    model = glm::translate( glm::mat4(1.0f), glm::vec3(4.0 * sin(angle), 0.0, 4.0 * cos(angle)));
    if(clockwise)
    {
        if(spinning)
            rotation -= .001;
        model = glm::rotate( model, rotation, glm::vec3(0, 1, 0) );
    }
    else
    {
        if(spinning)
            rotation += .001;
        model = glm::rotate( model, rotation, glm::vec3(0, 1, 0) );
    }
    // Update the state of the scene
    glutPostRedisplay();//call the display callback

    if(exit_flag)
    {
      glutDestroyMenu(optionsMenu);
      exit(0);
    }
}

void reshape(int n_w, int n_h)
{
    w = n_w;
    h = n_h;
    //Change the viewport to be correct
    glViewport( 0, 0, w, h);
    //Update the projection matrix as well
    //See the init function for an explaination
    projection = glm::perspective(45.0f, float(w)/float(h), 0.01f, 100.0f);

}

void keyboard(unsigned char key, int x_pos, int y_pos)
{
    switch (key)
    {
      case 27:  //ESC
        exit_flag = true;
        break;
      case 97:  //'a'
      case 65:  //'A'
        clockwise = false;
        break;
      case 100: //'d'
      case 68:  //'D'
        clockwise = true;
        break;
      default:  //Default
        break;
    }
}

void mouse(int button, int state, int x, int y)
{
  if(state == GLUT_UP)
  {
    switch(button)
    {
      case GLUT_LEFT_BUTTON:
        clockwise = !clockwise;
        break;
      default:
        break;
    }
  }
}

void menu(int index)
{
  //std::cout << index << std::endl;
  switch(index)
  {
    case 1: //Rotate
        spinning = !spinning;
      break;
    case 2: //Exit Program
        exit_flag = true;
      break;
    }
}

bool initialize()
{
    // Initialize basic geometry and shaders for this example

    //this defines a cube, this is why a model loader is nice
    //you can also do this with a draw elements and indices, try to get that working
    Vertex geometry[] = { {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
                          {{-1.0, -1.0, 1.0}, {0.0, 0.0, 1.0}},
                          {{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},

                          {{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},
                          {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
                          {{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},

                          {{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},
                          {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
                          {{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},

                          {{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},
                          {{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},
                          {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},

                          {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},
                          {{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},
                          {{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},

                          {{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},
                          {{-1.0, -1.0, 1.0}, {0.0, 0.0, 1.0}},
                          {{-1.0, -1.0, -1.0}, {0.0, 0.0, 0.0}},

                          {{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},
                          {{-1.0, -1.0, 1.0}, {0.0, 0.0, 1.0}},
                          {{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},

                          {{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
                          {{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},
                          {{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},

                          {{1.0, -1.0, -1.0}, {1.0, 0.0, 0.0}},
                          {{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
                          {{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}},

                          {{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
                          {{1.0, 1.0, -1.0}, {1.0, 1.0, 0.0}},
                          {{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},

                          {{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
                          {{-1.0, 1.0, -1.0}, {0.0, 1.0, 0.0}},
                          {{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},

                          {{1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}},
                          {{-1.0, 1.0, 1.0}, {0.0, 1.0, 1.0}},
                          {{1.0, -1.0, 1.0}, {1.0, 0.0, 1.0}}
                        };
    // Create a Vertex Buffer object to store this vertex info on the GPU
    glGenBuffers(1, &vbo_geometry);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_geometry);
    glBufferData(GL_ARRAY_BUFFER, sizeof(geometry), geometry, GL_STATIC_DRAW);

    //--Geometry done

    ShaderLoader shaderLoader = ShaderLoader(
        "defaultVertexShader.vs", "defaultFragmentShader.fs");
    program = shaderLoader.loadShader();
    glUseProgram(program);

    //Now we set the locations of the attributes and uniforms
    //this allows us to access them easily while rendering
    loc_position = glGetAttribLocation(program,
                    const_cast<const char*>("v_position"));
    if(loc_position == -1)
    {
        std::cerr << "[F] POSITION NOT FOUND" << std::endl;
        return false;
    }

    loc_color = glGetAttribLocation(program,
                    const_cast<const char*>("v_color"));
    if(loc_color == -1)
    {
        std::cerr << "[F] V_COLOR NOT FOUND" << std::endl;
        return false;
    }

    loc_mvpmat = glGetUniformLocation(program,
                    const_cast<const char*>("mvpMatrix"));
    if(loc_mvpmat == -1)
    {
        std::cerr << "[F] MVPMATRIX NOT FOUND" << std::endl;
        return false;
    }

    //--Init the view and projection matrices
    //  if you will be having a moving camera the view matrix will need to more dynamic
    //  ...Like you should update it before you render more dynamic
    //  for this project having them static will be fine
    view = glm::lookAt( glm::vec3(0.0, 8.0, -16.0), //Eye Position
                        glm::vec3(0.0, 0.0, 0.0), //Focus point
                        glm::vec3(0.0, 1.0, 0.0)); //Positive Y is up

    projection = glm::perspective( 45.0f, //the FoV typically 90 degrees is good which is what this is set to
                                   float(w)/float(h), //Aspect Ratio, so Circles stay Circular
                                   0.01f, //Distance to the near plane, normally a small value like this
                                   100.0f); //Distance to the far plane,

    //enable depth testing
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    //and its done
    return true;
}

void cleanUp()
{
    // Clean up, Clean up
    glDeleteProgram(program);
    glDeleteBuffers(1, &vbo_geometry);
}

//returns the time delta
float getDT()
{
    float ret;
    t2 = std::chrono::high_resolution_clock::now();
    ret = std::chrono::duration_cast< std::chrono::duration<float> >(t2-t1).count();
    t1 = std::chrono::high_resolution_clock::now();
    return ret;
}<|endoftext|>


<commit_before>#include <iostream>
#include <type_traits>

template<int N, typename std::enable_if<N == 1, bool>::type = true> void  print();
template<int N, typename std::enable_if<N % 5 != 0 && N % 3 == 0, bool>::type = true> void print();
template<int N, typename std::enable_if<N % 5 == 0 && N % 3 != 0, bool>::type = true> void print();
template<int N, typename std::enable_if<N % 15 == 0, bool>::type = true> void print();
template<int N, typename std::enable_if<N % 5 != 0 && N % 3 != 0 && N != 1, bool>::type = true> void print();

template<int N, typename std::enable_if<N % 5 != 0 && N % 3 == 0, bool>::type> void print()
{
   print<N-1>();
   std::cout << "Fizz" << std::endl;
}

template<int N, typename std::enable_if<N % 5 == 0 && N % 3 != 0, bool>::type> void print()
{
   print<N-1>();
   std::cout << "Buzz" << std::endl;
}

template<int N, typename std::enable_if<N % 15 == 0, bool>::type> void print()
{
   print<N-1>();
   std::cout << "Fizzbuzz" << std::endl;
}

template<int N, typename std::enable_if<N == 1, bool>::type> void  print()
{
   std::cout << 1 << std::endl;
}

template<int N, typename std::enable_if<N % 5 != 0 && N % 3 != 0 && N != 1, bool>::type> void print()
{
   print<N-1>();
   std::cout << N << std::endl;
}

int main (int argc, char *argv[])
{
   print<100>();
}

<commit_msg>The 'b' in FizzBuzz should be upper-case.<commit_after>#include <iostream>
#include <type_traits>

template<int N, typename std::enable_if<N == 1, bool>::type = true> void  print();
template<int N, typename std::enable_if<N % 5 != 0 && N % 3 == 0, bool>::type = true> void print();
template<int N, typename std::enable_if<N % 5 == 0 && N % 3 != 0, bool>::type = true> void print();
template<int N, typename std::enable_if<N % 15 == 0, bool>::type = true> void print();
template<int N, typename std::enable_if<N % 5 != 0 && N % 3 != 0 && N != 1, bool>::type = true> void print();

template<int N, typename std::enable_if<N % 5 != 0 && N % 3 == 0, bool>::type> void print()
{
   print<N-1>();
   std::cout << "Fizz" << std::endl;
}

template<int N, typename std::enable_if<N % 5 == 0 && N % 3 != 0, bool>::type> void print()
{
   print<N-1>();
   std::cout << "Buzz" << std::endl;
}

template<int N, typename std::enable_if<N % 15 == 0, bool>::type> void print()
{
   print<N-1>();
   std::cout << "FizzBuzz" << std::endl;
}

template<int N, typename std::enable_if<N == 1, bool>::type> void  print()
{
   std::cout << 1 << std::endl;
}

template<int N, typename std::enable_if<N % 5 != 0 && N % 3 != 0 && N != 1, bool>::type> void print()
{
   print<N-1>();
   std::cout << N << std::endl;
}

int main (int argc, char *argv[])
{
   print<100>();
}

<|endoftext|>


<commit_before>#include <string>
#include <map>
#include <iostream>
#include <memory>
#include <sstream>

#include "camera.h"
#include "integrator.h"
#include "dintegrator.h"
#include "scene.h"
#include "kdscene.h"
#include "bsdf.h"
#include "path_tracer.h"
#include "directlightingintegrator.h"
#include "util.h"
#include "model.h"
#include "material.h"
#include "scenes/basic_scenes.h"
#include "reinhard.h"
#include "cpp-optparse/OptionParser.h"
#include "util/timer.h"
#include "util/running_stats.h"
#include "thread_state.h"

using std::cerr;
using std::endl;
using std::cout;
using std::map;
using std::vector;
using std::make_unique;
using std::make_shared;

void usage(char** args)
{
  cerr << args[0] << ": WIDTH HEIGHT SAMPLES-PER-PIXEL\n";
}

const  map<string, DebugIntegrator::Type> DEBUG_TYPE_MAP({
    {"isect", DebugIntegrator::Type::DI_ISECT},
    {"object_id", DebugIntegrator::Type::DI_OBJECT_ID},
    {"normal", DebugIntegrator::Type::DI_NORMAL},
    {"depth", DebugIntegrator::Type::DI_DEPTH},
    {"specular", DebugIntegrator::Type::DI_SPECULAR},
    {"first_env", DebugIntegrator::Type::DI_FIRST_ENV},
    {"time_intersect", DebugIntegrator::Type::DI_TIME_INTERSECT}
  });

auto parse_args(int argc, char**args)
{
  optparse::OptionParser parser;

  vector<string> debug_map_keys;
  std::transform(DEBUG_TYPE_MAP.begin(), DEBUG_TYPE_MAP.end(),
                 std::inserter(debug_map_keys, debug_map_keys.end()), [](const auto& e) { return e.first; });

  parser.add_option("-w", "--width").action("store").type("int").set_default(400);
  parser.add_option("-h", "--height").action("store").type("int").set_default(300);
  parser.add_option("-t", "--threads").action("store").type("int").set_default(0);
  parser.add_option("-s", "--samples").action("store").type("int").set_default(1);
  parser.add_option("-b", "--benchmark").action("store").type("int").set_default(1);
  parser.add_option("-o", "--output_image").action("store_true").type("bool");
  parser.add_option("-q", "--no_image").action("store_false").dest("output_image");
  parser.add_option("-d", "--debug_type").action("store").choices(debug_map_keys).set_default("normal");
  parser.add_option("-i", "--integrator").action("store").choices(std::vector<string>({"path", "direct", "debug"})).set_default("path");
  parser.add_option("-m", "--mapper").action("store").choices(std::vector<string>({"linear", "cutoff", "rh_global"})).set_default("linear");
  parser.add_option("--kd").action("store_const").dest("scene_container").set_const("kd");
  parser.add_option("--basic").action("store_const").dest("scene_container").set_const("basic");

  parser.set_defaults("output_image", "true");
  parser.set_defaults("scene_container", "kd");

  return parser.parse_args(argc, args);
}

int main(int argc, char** args)
{
  auto options = parse_args(argc, args);

  const uint WIDTH = options.get("width").as<int>();
  const uint HEIGHT = options.get("height").as<int>();

  assert(WIDTH > 0);
  assert(HEIGHT > 0);

  const uint per_pixel = options.get("samples").as<int>();
  assert(per_pixel > 0);

  shared_ptr<Scene> scene;
  if (options["scene_container"] == "kd")
    scene = make_shared<KDScene>();
  else
    scene = make_shared<BasicScene>();

  //auto cam = model_scene(*scene, aspect, "assets/models/trumpet.obj", false);
  auto cam = lua_scene(*scene, "assets/scripts/scene1.lua");

  Film f(WIDTH, HEIGHT);

  register_thread_state_manager(f, "assets/scripts/test.lua");
  auto num_threads = options.get("threads").as<int>();
  if (num_threads == 0)
    num_threads = num_system_procs();
  cerr << "using " << num_threads << " threads.\n";

  auto scheduler = make_scheduler(num_threads);

  unique_ptr<Integrator> igr;
  string igr_type = options["integrator"];

  if (igr_type == "path")
  {
    PathTracerIntegrator::Options opt;
    opt.samples_per_pixel = per_pixel;
    opt.max_depth = 10;
    igr = make_unique<PathTracerIntegrator>(opt);
  }
  else if (igr_type == "direct")
  {
    DirectLightingIntegrator::Options opt;
    opt.samples_per_pixel = 4;
    opt.lighting_samples = per_pixel / 4;
    opt.subdivision = 4;
    igr = make_unique<DirectLightingIntegrator>(opt);
  }
  else // if (igr_type == "debug")
  {
    DebugIntegrator::Options opt;
    string dt = options.get("debug_type");
    opt.type = DEBUG_TYPE_MAP.at(dt);
    opt.samples_per_pixel = per_pixel;
    igr = make_unique<DebugIntegrator>(opt);
  }

  {
    Timer tm;
    scene->prepare();
    cerr << "Prepared scene in " << format_duration(tm.since()) << endl;
  }

  scalar render_time = 0;

  auto benchmark_trials = options.get("benchmark").as<int>();
  bool write_image =  options.get("output_image").as<bool>();
  if (benchmark_trials > 1)
  {
    write_image = false;
    RunningStats stats;

    cerr << "Benchmarking with " << benchmark_trials << " trials" << endl;
    const int toss = 3;

    for (int i = 0; i < benchmark_trials + toss; i += 1)
    {
      Film f(WIDTH, HEIGHT);
      Timer tm;
      igr->render(*cam, *scene, *scheduler, f);
      if (i >= toss)
        stats.update(tm.since());
    }

    cerr << "Render Time: " << format_duration(stats.mean()) << " +/- "
         << format_duration(stats.stdev()) << endl;
  }
  else
  {
    Timer tm;
    igr->render(*cam, *scene, *scheduler, f);
    render_time = tm.since();
    cerr << "Render Time: " << format_duration(render_time) << endl;
  }

  shared_ptr<ToneMapper> mapper;
  string map_type = options.get("mapper");
  if (map_type == "cutoff")
  {
    mapper = make_shared<CutoffToneMapper>();
  }
  else if (map_type == "linear")
  {
    mapper = make_shared<LinearToneMapper>();
  }
  else if (map_type == "rh_global")
  {
    mapper = make_shared<ReinhardGlobal>();
  }

  if (write_image)
    f.render_to_ppm(cout, *mapper);

  return 0;
}
<commit_msg>Removes aspect parameter from main scene call<commit_after>#include <string>
#include <map>
#include <iostream>
#include <memory>
#include <sstream>

#include "camera.h"
#include "integrator.h"
#include "dintegrator.h"
#include "scene.h"
#include "kdscene.h"
#include "bsdf.h"
#include "path_tracer.h"
#include "directlightingintegrator.h"
#include "util.h"
#include "model.h"
#include "material.h"
#include "scenes/basic_scenes.h"
#include "reinhard.h"
#include "cpp-optparse/OptionParser.h"
#include "util/timer.h"
#include "util/running_stats.h"
#include "thread_state.h"

using std::cerr;
using std::endl;
using std::cout;
using std::map;
using std::vector;
using std::make_unique;
using std::make_shared;

void usage(char** args)
{
  cerr << args[0] << ": WIDTH HEIGHT SAMPLES-PER-PIXEL\n";
}

const  map<string, DebugIntegrator::Type> DEBUG_TYPE_MAP({
    {"isect", DebugIntegrator::Type::DI_ISECT},
    {"object_id", DebugIntegrator::Type::DI_OBJECT_ID},
    {"normal", DebugIntegrator::Type::DI_NORMAL},
    {"depth", DebugIntegrator::Type::DI_DEPTH},
    {"specular", DebugIntegrator::Type::DI_SPECULAR},
    {"first_env", DebugIntegrator::Type::DI_FIRST_ENV},
    {"time_intersect", DebugIntegrator::Type::DI_TIME_INTERSECT}
  });

auto parse_args(int argc, char**args)
{
  optparse::OptionParser parser;

  vector<string> debug_map_keys;
  std::transform(DEBUG_TYPE_MAP.begin(), DEBUG_TYPE_MAP.end(),
                 std::inserter(debug_map_keys, debug_map_keys.end()), [](const auto& e) { return e.first; });

  parser.add_option("-w", "--width").action("store").type("int").set_default(400);
  parser.add_option("-h", "--height").action("store").type("int").set_default(300);
  parser.add_option("-t", "--threads").action("store").type("int").set_default(0);
  parser.add_option("-s", "--samples").action("store").type("int").set_default(1);
  parser.add_option("-b", "--benchmark").action("store").type("int").set_default(1);
  parser.add_option("-o", "--output_image").action("store_true").type("bool");
  parser.add_option("-q", "--no_image").action("store_false").dest("output_image");
  parser.add_option("-d", "--debug_type").action("store").choices(debug_map_keys).set_default("normal");
  parser.add_option("-i", "--integrator").action("store").choices(std::vector<string>({"path", "direct", "debug"})).set_default("path");
  parser.add_option("-m", "--mapper").action("store").choices(std::vector<string>({"linear", "cutoff", "rh_global"})).set_default("linear");
  parser.add_option("--kd").action("store_const").dest("scene_container").set_const("kd");
  parser.add_option("--basic").action("store_const").dest("scene_container").set_const("basic");

  parser.set_defaults("output_image", "true");
  parser.set_defaults("scene_container", "kd");

  return parser.parse_args(argc, args);
}

int main(int argc, char** args)
{
  auto options = parse_args(argc, args);

  const uint WIDTH = options.get("width").as<int>();
  const uint HEIGHT = options.get("height").as<int>();

  assert(WIDTH > 0);
  assert(HEIGHT > 0);

  const uint per_pixel = options.get("samples").as<int>();
  assert(per_pixel > 0);

  shared_ptr<Scene> scene;
  if (options["scene_container"] == "kd")
    scene = make_shared<KDScene>();
  else
    scene = make_shared<BasicScene>();

  //auto cam = model_scene(*scene, "assets/models/tak-cube.obj", false);
  auto cam = lua_scene(*scene, "assets/scripts/scene1.lua");

  Film f(WIDTH, HEIGHT);

  register_thread_state_manager(f, "assets/scripts/test.lua");
  auto num_threads = options.get("threads").as<int>();
  if (num_threads == 0)
    num_threads = num_system_procs();
  cerr << "using " << num_threads << " threads.\n";

  auto scheduler = make_scheduler(num_threads);

  unique_ptr<Integrator> igr;
  string igr_type = options["integrator"];

  if (igr_type == "path")
  {
    PathTracerIntegrator::Options opt;
    opt.samples_per_pixel = per_pixel;
    opt.max_depth = 10;
    igr = make_unique<PathTracerIntegrator>(opt);
  }
  else if (igr_type == "direct")
  {
    DirectLightingIntegrator::Options opt;
    opt.samples_per_pixel = 4;
    opt.lighting_samples = per_pixel / 4;
    opt.subdivision = 4;
    igr = make_unique<DirectLightingIntegrator>(opt);
  }
  else // if (igr_type == "debug")
  {
    DebugIntegrator::Options opt;
    string dt = options.get("debug_type");
    opt.type = DEBUG_TYPE_MAP.at(dt);
    opt.samples_per_pixel = per_pixel;
    igr = make_unique<DebugIntegrator>(opt);
  }

  {
    Timer tm;
    scene->prepare();
    cerr << "Prepared scene in " << format_duration(tm.since()) << endl;
  }

  scalar render_time = 0;

  auto benchmark_trials = options.get("benchmark").as<int>();
  bool write_image =  options.get("output_image").as<bool>();
  if (benchmark_trials > 1)
  {
    write_image = false;
    RunningStats stats;

    cerr << "Benchmarking with " << benchmark_trials << " trials" << endl;
    const int toss = 3;

    for (int i = 0; i < benchmark_trials + toss; i += 1)
    {
      Film f(WIDTH, HEIGHT);
      Timer tm;
      igr->render(*cam, *scene, *scheduler, f);
      if (i >= toss)
        stats.update(tm.since());
    }

    cerr << "Render Time: " << format_duration(stats.mean()) << " +/- "
         << format_duration(stats.stdev()) << endl;
  }
  else
  {
    Timer tm;
    igr->render(*cam, *scene, *scheduler, f);
    render_time = tm.since();
    cerr << "Render Time: " << format_duration(render_time) << endl;
  }

  shared_ptr<ToneMapper> mapper;
  string map_type = options.get("mapper");
  if (map_type == "cutoff")
  {
    mapper = make_shared<CutoffToneMapper>();
  }
  else if (map_type == "linear")
  {
    mapper = make_shared<LinearToneMapper>();
  }
  else if (map_type == "rh_global")
  {
    mapper = make_shared<ReinhardGlobal>();
  }

  if (write_image)
    f.render_to_ppm(cout, *mapper);

  return 0;
}
<|endoftext|>