<commit_before>/*
 * Copyright © 2008, 2009 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
#include <cstdlib>
#include <cstdio>
#include <getopt.h>

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

extern "C" {
#include <talloc.h>
}

#include "ast.h"
#include "glsl_parser_extras.h"
#include "glsl_parser.h"
#include "ir_optimization.h"
#include "ir_print_visitor.h"
#include "program.h"

static char *
load_text_file(const char *file_name, size_t *size)
{
	char *text = NULL;
	struct stat st;
	ssize_t total_read = 0;
	int fd = open(file_name, O_RDONLY);

	*size = 0;
	if (fd < 0) {
		return NULL;
	}

	if (fstat(fd, & st) == 0) {
	   text = (char *) malloc(st.st_size + 1);
		if (text != NULL) {
			do {
				ssize_t bytes = read(fd, text + total_read,
						     st.st_size - total_read);
				if (bytes < 0) {
					free(text);
					text = NULL;
					break;
				}

				if (bytes == 0) {
					break;
				}

				total_read += bytes;
			} while (total_read < st.st_size);

			text[total_read] = '\0';
			*size = total_read;
		}
	}

	close(fd);

	return text;
}

void
usage_fail(const char *name)
{
      printf("%s <filename.frag|filename.vert>\n", name);
      exit(EXIT_FAILURE);
}

int dump_ast = 0;
int dump_lir = 0;
int do_link = 0;

const struct option compiler_opts[] = {
   { "dump-ast", 0, &dump_ast, 1 },
   { "dump-lir", 0, &dump_lir, 1 },
   { "link",     0, &do_link,  1 },
   { NULL, 0, NULL, 0 }
};

void
compile_shader(struct glsl_shader *shader)
{
   struct _mesa_glsl_parse_state state;

   memset(& state, 0, sizeof(state));
   switch (shader->Type) {
   case GL_VERTEX_SHADER:   state.target = vertex_shader; break;
   case GL_FRAGMENT_SHADER: state.target = fragment_shader; break;
   case GL_GEOMETRY_SHADER: state.target = geometry_shader; break;
   }

   state.scanner = NULL;
   state.translation_unit.make_empty();
   state.symbols = new glsl_symbol_table;
   state.info_log = talloc_strdup(shader, "");
   state.error = false;
   state.temp_index = 0;
   state.loop_or_switch_nesting = NULL;
   state.ARB_texture_rectangle_enable = true;

   _mesa_glsl_lexer_ctor(& state, shader->Source, shader->SourceLen);
   _mesa_glsl_parse(& state);
   _mesa_glsl_lexer_dtor(& state);

   if (dump_ast) {
      foreach_list_const(n, &state.translation_unit) {
	 ast_node *ast = exec_node_data(ast_node, n, link);
	 ast->print();
      }
      printf("\n\n");
   }

   shader->ir.make_empty();
   if (!state.error && !state.translation_unit.is_empty())
      _mesa_ast_to_hir(&shader->ir, &state);

   /* Optimization passes */
   if (!state.error && !shader->ir.is_empty()) {
      bool progress;
      do {
	 progress = false;

	 progress = do_function_inlining(&shader->ir) || progress;
	 progress = do_if_simplification(&shader->ir) || progress;
	 progress = do_copy_propagation(&shader->ir) || progress;
	 progress = do_dead_code_local(&shader->ir) || progress;
	 progress = do_dead_code_unlinked(&shader->ir) || progress;
	 progress = do_constant_variable_unlinked(&shader->ir) || progress;
	 progress = do_constant_folding(&shader->ir) || progress;
	 progress = do_vec_index_to_swizzle(&shader->ir) || progress;
	 progress = do_swizzle_swizzle(&shader->ir) || progress;
      } while (progress);
   }

   /* Print out the resulting IR */
   if (!state.error && dump_lir) {
      _mesa_print_ir(&shader->ir, &state);
   }

   shader->symbols = state.symbols;
   shader->CompileStatus = !state.error;

   if (shader->InfoLog)
      talloc_free(shader->InfoLog);

   shader->InfoLog = state.info_log;

   return;
}

int
main(int argc, char **argv)
{
   int status = EXIT_SUCCESS;

   int c;
   int idx = 0;
   while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1)
      /* empty */ ;

   if (argc <= optind)
      usage_fail(argv[0]);

   struct glsl_program whole_program;
   memset(&whole_program, 0, sizeof(whole_program));

   for (/* empty */; argc > optind; optind++) {
      whole_program.Shaders = (struct glsl_shader **)
	 realloc(whole_program.Shaders,
		 sizeof(struct glsl_shader *) * (whole_program.NumShaders + 1));
      assert(whole_program.Shaders != NULL);

      /* talloc context should probably be whole_program */
      struct glsl_shader *shader = talloc_zero(NULL, glsl_shader);

      whole_program.Shaders[whole_program.NumShaders] = shader;
      whole_program.NumShaders++;

      const unsigned len = strlen(argv[optind]);
      if (len < 6)
	 usage_fail(argv[0]);

      const char *const ext = & argv[optind][len - 5];
      if (strncmp(".vert", ext, 5) == 0)
	 shader->Type = GL_VERTEX_SHADER;
      else if (strncmp(".geom", ext, 5) == 0)
	 shader->Type = GL_GEOMETRY_SHADER;
      else if (strncmp(".frag", ext, 5) == 0)
	 shader->Type = GL_FRAGMENT_SHADER;
      else
	 usage_fail(argv[0]);

      shader->Source = load_text_file(argv[optind], &shader->SourceLen);

      compile_shader(shader);

      if (!shader->CompileStatus) {
	 printf("Info log for %s:\n%s\n", argv[optind], shader->InfoLog);
	 status = EXIT_FAILURE;
	 break;
      }
   }

   if ((status == EXIT_SUCCESS) && do_link)  {
      link_shaders(&whole_program);
      status = (whole_program.LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE;
   }

   return status;
}
<commit_msg>Complain and exit if the given shader file doesn't exist.<commit_after>/*
 * Copyright © 2008, 2009 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
#include <cstdlib>
#include <cstdio>
#include <getopt.h>

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

extern "C" {
#include <talloc.h>
}

#include "ast.h"
#include "glsl_parser_extras.h"
#include "glsl_parser.h"
#include "ir_optimization.h"
#include "ir_print_visitor.h"
#include "program.h"

static char *
load_text_file(const char *file_name, size_t *size)
{
	char *text = NULL;
	struct stat st;
	ssize_t total_read = 0;
	int fd = open(file_name, O_RDONLY);

	*size = 0;
	if (fd < 0) {
		return NULL;
	}

	if (fstat(fd, & st) == 0) {
	   text = (char *) malloc(st.st_size + 1);
		if (text != NULL) {
			do {
				ssize_t bytes = read(fd, text + total_read,
						     st.st_size - total_read);
				if (bytes < 0) {
					free(text);
					text = NULL;
					break;
				}

				if (bytes == 0) {
					break;
				}

				total_read += bytes;
			} while (total_read < st.st_size);

			text[total_read] = '\0';
			*size = total_read;
		}
	}

	close(fd);

	return text;
}

void
usage_fail(const char *name)
{
      printf("%s <filename.frag|filename.vert>\n", name);
      exit(EXIT_FAILURE);
}

int dump_ast = 0;
int dump_lir = 0;
int do_link = 0;

const struct option compiler_opts[] = {
   { "dump-ast", 0, &dump_ast, 1 },
   { "dump-lir", 0, &dump_lir, 1 },
   { "link",     0, &do_link,  1 },
   { NULL, 0, NULL, 0 }
};

void
compile_shader(struct glsl_shader *shader)
{
   struct _mesa_glsl_parse_state state;

   memset(& state, 0, sizeof(state));
   switch (shader->Type) {
   case GL_VERTEX_SHADER:   state.target = vertex_shader; break;
   case GL_FRAGMENT_SHADER: state.target = fragment_shader; break;
   case GL_GEOMETRY_SHADER: state.target = geometry_shader; break;
   }

   state.scanner = NULL;
   state.translation_unit.make_empty();
   state.symbols = new glsl_symbol_table;
   state.info_log = talloc_strdup(shader, "");
   state.error = false;
   state.temp_index = 0;
   state.loop_or_switch_nesting = NULL;
   state.ARB_texture_rectangle_enable = true;

   _mesa_glsl_lexer_ctor(& state, shader->Source, shader->SourceLen);
   _mesa_glsl_parse(& state);
   _mesa_glsl_lexer_dtor(& state);

   if (dump_ast) {
      foreach_list_const(n, &state.translation_unit) {
	 ast_node *ast = exec_node_data(ast_node, n, link);
	 ast->print();
      }
      printf("\n\n");
   }

   shader->ir.make_empty();
   if (!state.error && !state.translation_unit.is_empty())
      _mesa_ast_to_hir(&shader->ir, &state);

   /* Optimization passes */
   if (!state.error && !shader->ir.is_empty()) {
      bool progress;
      do {
	 progress = false;

	 progress = do_function_inlining(&shader->ir) || progress;
	 progress = do_if_simplification(&shader->ir) || progress;
	 progress = do_copy_propagation(&shader->ir) || progress;
	 progress = do_dead_code_local(&shader->ir) || progress;
	 progress = do_dead_code_unlinked(&shader->ir) || progress;
	 progress = do_constant_variable_unlinked(&shader->ir) || progress;
	 progress = do_constant_folding(&shader->ir) || progress;
	 progress = do_vec_index_to_swizzle(&shader->ir) || progress;
	 progress = do_swizzle_swizzle(&shader->ir) || progress;
      } while (progress);
   }

   /* Print out the resulting IR */
   if (!state.error && dump_lir) {
      _mesa_print_ir(&shader->ir, &state);
   }

   shader->symbols = state.symbols;
   shader->CompileStatus = !state.error;

   if (shader->InfoLog)
      talloc_free(shader->InfoLog);

   shader->InfoLog = state.info_log;

   return;
}

int
main(int argc, char **argv)
{
   int status = EXIT_SUCCESS;

   int c;
   int idx = 0;
   while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1)
      /* empty */ ;

   if (argc <= optind)
      usage_fail(argv[0]);

   struct glsl_program whole_program;
   memset(&whole_program, 0, sizeof(whole_program));

   for (/* empty */; argc > optind; optind++) {
      whole_program.Shaders = (struct glsl_shader **)
	 realloc(whole_program.Shaders,
		 sizeof(struct glsl_shader *) * (whole_program.NumShaders + 1));
      assert(whole_program.Shaders != NULL);

      /* talloc context should probably be whole_program */
      struct glsl_shader *shader = talloc_zero(NULL, glsl_shader);

      whole_program.Shaders[whole_program.NumShaders] = shader;
      whole_program.NumShaders++;

      const unsigned len = strlen(argv[optind]);
      if (len < 6)
	 usage_fail(argv[0]);

      const char *const ext = & argv[optind][len - 5];
      if (strncmp(".vert", ext, 5) == 0)
	 shader->Type = GL_VERTEX_SHADER;
      else if (strncmp(".geom", ext, 5) == 0)
	 shader->Type = GL_GEOMETRY_SHADER;
      else if (strncmp(".frag", ext, 5) == 0)
	 shader->Type = GL_FRAGMENT_SHADER;
      else
	 usage_fail(argv[0]);

      shader->Source = load_text_file(argv[optind], &shader->SourceLen);
      if (shader->Source == NULL) {
	 printf("File \"%s\" does not exist.\n", argv[optind]);
	 exit(EXIT_FAILURE);
      }

      compile_shader(shader);

      if (!shader->CompileStatus) {
	 printf("Info log for %s:\n%s\n", argv[optind], shader->InfoLog);
	 status = EXIT_FAILURE;
	 break;
      }
   }

   if ((status == EXIT_SUCCESS) && do_link)  {
      link_shaders(&whole_program);
      status = (whole_program.LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE;
   }

   return status;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <chrono>
#include <random>
#include <vector>

#include <SFML/System/Vector2.hpp>
#include <SFML/Graphics/Image.hpp>

bool done = false;

std::mt19937 generator;
std::uniform_real_distribution<double> heightDist(0, 1);
std::uniform_int_distribution<int> startDist(-10000, 10000);

sf::Vector2u size;
std::vector<double> heights;
void divideSquare(bool first, unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4);

int main(int argc, char** argv)
{
	if(argc != 3)
	{
		std::cerr << "Incorrect # of args, must be 2.\n";
		return 1;
	}

	size = {static_cast<unsigned>(std::stoi(argv[1])), static_cast<unsigned>(std::stoi(argv[2]))};
	// resize vector to correct size
	heights.resize(size.x * size.y, 0);

	// seed generator
	generator.seed(std::chrono::system_clock::now().time_since_epoch().count());

	// make the image
	sf::Image heightMap;
	heightMap.create(size.x, size.y);

	// begin the recursive algo!
	divideSquare(true, 0, 0, size.x, size.y, -1, -1, -1, -1);

	// fill the image
	for(unsigned i = 0; i < size.x * size.y; i++)
	{
		sf::Uint8 r = 255.0 * heights[i];
		sf::Uint8 g = 255.0 * heights[i];
		sf::Uint8 b = 255.0 * heights[i];

		heightMap.setPixel(i % size.x, i / size.y, {r, g, b});
	}

	heightMap.saveToFile("img" + std::to_string(std::chrono::system_clock::now().time_since_epoch().count()) + ".png");

	return 0;
}

void divideSquare(bool first, unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4)
{
	// get corners
	double topLeft, topRight, botLeft, botRight;

	if((c1 == -1 && c2 == -1 && c3 == -1 && c4 == -1) || first)
	{
		topLeft = heightDist(generator);
		topRight = heightDist(generator);
		botLeft = heightDist(generator);
		botRight = heightDist(generator);
	}
	else
	{
		topLeft = c1;
		topRight = c2;
		botLeft = c3;
		botRight = c4;
	}

	// get midpoints on edges
	double topEdge, leftEdge, rightEdge, botEdge;

	if(first)
	{
		topEdge = heightDist(generator);
		leftEdge = heightDist(generator);
		rightEdge = heightDist(generator);
		botEdge = heightDist(generator);
	}
	else
	{
		topEdge = (topLeft + topRight) / 2.0;
		leftEdge = (topLeft + botLeft) / 2.0;
		rightEdge = (topRight + botRight) / 2.0;
		botEdge = (botLeft + botRight) / 2.0;
	}

	// middle point of the square, add a random amount to keep the map less uniform
	double middle;

	if(first)
		middle = heightDist(generator);
	else
		middle = (topLeft + topRight + botLeft + botRight + heightDist(generator)) / 5.0;

	// assign values
	// corners
	heights[(x % size.x) + (y % size.y) * size.x] = topLeft;
	heights[(x + w) % size.x + (y % size.y) * size.x] = topRight;
	heights[(x % size.x) + ((y + h) % size.y) * size.x] = botLeft;
	heights[(x + w) % size.x + ((y + h) % size.y) * size.x] = botRight;

	// midpoints
	heights[(x + (w / 2)) % size.x + (y % size.y) * size.x] = topEdge;
	heights[(x % size.x) + ((y + (h / 2)) % size.y) * size.x] = leftEdge;
	heights[(x + w) % size.x + ((y + (h / 2)) % size.y) * size.x] = rightEdge;
	heights[(x + (w / 2)) % size.x + ((y + h) % size.y) * size.x] = botEdge;
	heights[(x + (w / 2)) % size.x + ((y + (h / 2)) % size.y) * size.x] = middle;

	// if we're too small to continue
	if(!(w > 1 || h > 1))
		return;

	divideSquare(false, x, y, w / 2.0, h / 2.0, topLeft, topEdge, leftEdge, middle);	// top left quad
	divideSquare(false, x + w / 2.0, y, w / 2.0, h / 2.0, topEdge, topRight, middle, rightEdge);	// top right quad
	divideSquare(false, x, y + h / 2.0, w / 2.0, h / 2.0, leftEdge, middle, botLeft, botEdge);	// bot left quad
	divideSquare(false, x + w / 2.0, y + h / 2.0, w / 2.0, h / 2.0, middle, rightEdge, botEdge, botRight);	// bot right quad
}
<commit_msg>Added a roughness parameter<commit_after>#include <iostream>
#include <chrono>
#include <random>
#include <vector>

#include <SFML/System/Vector2.hpp>
#include <SFML/Graphics/Image.hpp>

bool done = false;

std::mt19937 generator;
std::uniform_real_distribution<double> heightDist(0, 1);
std::uniform_real_distribution<double> roughDist;
std::uniform_int_distribution<int> startDist(-10000, 10000);

sf::Vector2u size;
std::vector<double> heights;
void divideSquare(bool first, unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4);

int main(int argc, char** argv)
{
	if(argc != 4)
	{
		std::cerr << "Incorrect # of args, must be 3.\n";
		return 1;
	}

	size = {static_cast<unsigned>(std::stoi(argv[1])), static_cast<unsigned>(std::stoi(argv[2]))};

	// resize vector to correct size
	heights.resize(size.x * size.y, 0);

	double roughness = std::stod(argv[3]);

	// clamp roughness variable to 0..1
	if(roughness < 0)
		roughness = 0;
	if(roughness > 1)
		roughness = 1;

	roughDist = std::uniform_real_distribution<double>(-roughness, roughness);

	// seed generator
	generator.seed(std::chrono::system_clock::now().time_since_epoch().count());

	// make the image
	sf::Image heightMap;
	heightMap.create(size.x, size.y);

	// begin the recursive algo!
	divideSquare(true, 0, 0, size.x, size.y, -1, -1, -1, -1);

	// fill the image
	for(unsigned i = 0; i < size.x * size.y; i++)
	{
		sf::Uint8 r = 255.0 * heights[i];
		sf::Uint8 g = 255.0 * heights[i];
		sf::Uint8 b = 255.0 * heights[i];

		heightMap.setPixel(i % size.x, i / size.y, {r, g, b});
	}

	heightMap.saveToFile("img" + std::to_string(std::chrono::system_clock::now().time_since_epoch().count()) + ".png");

	return 0;
}

void divideSquare(bool first, unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4)
{
	// get corners
	double topLeft, topRight, botLeft, botRight;

	if((c1 == -1 && c2 == -1 && c3 == -1 && c4 == -1) || first)
	{
		topLeft = heightDist(generator);
		topRight = heightDist(generator);
		botLeft = heightDist(generator);
		botRight = heightDist(generator);
	}
	else
	{
		topLeft = c1;
		topRight = c2;
		botLeft = c3;
		botRight = c4;
	}

	// get midpoints on edges
	double topEdge, leftEdge, rightEdge, botEdge;

	if(first)
	{
		topEdge = heightDist(generator);
		leftEdge = heightDist(generator);
		rightEdge = heightDist(generator);
		botEdge = heightDist(generator);
	}
	else
	{
		topEdge = (topLeft + topRight) / 2.0;
		leftEdge = (topLeft + botLeft) / 2.0;
		rightEdge = (topRight + botRight) / 2.0;
		botEdge = (botLeft + botRight) / 2.0;
	}

	// middle point of the square, add a random amount to keep the map less uniform
	double middle;

	if(first)
		middle = heightDist(generator);
	else
		//middle = (topLeft + topRight + botLeft + botRight + heightDist(generator)) / 5.0;
		middle = (topLeft + topRight + botLeft + botRight) / 4.0 + roughDist(generator);

	// keep bounds
	if(middle < 0)
		middle = 0;
	if(middle > 1)
		middle = 1;

	// assign values
	// corners
	heights[(x % size.x) + (y % size.y) * size.x] = topLeft;
	heights[(x + w) % size.x + (y % size.y) * size.x] = topRight;
	heights[(x % size.x) + ((y + h) % size.y) * size.x] = botLeft;
	heights[(x + w) % size.x + ((y + h) % size.y) * size.x] = botRight;

	// midpoints
	heights[(x + (w / 2)) % size.x + (y % size.y) * size.x] = topEdge;
	heights[(x % size.x) + ((y + (h / 2)) % size.y) * size.x] = leftEdge;
	heights[(x + w) % size.x + ((y + (h / 2)) % size.y) * size.x] = rightEdge;
	heights[(x + (w / 2)) % size.x + ((y + h) % size.y) * size.x] = botEdge;
	heights[(x + (w / 2)) % size.x + ((y + (h / 2)) % size.y) * size.x] = middle;

	// if we're too small to continue
	if(!(w > 1 || h > 1))
		return;

	divideSquare(false, x, y, w / 2.0, h / 2.0, topLeft, topEdge, leftEdge, middle);	// top left quad
	divideSquare(false, x + w / 2.0, y, w / 2.0, h / 2.0, topEdge, topRight, middle, rightEdge);	// top right quad
	divideSquare(false, x, y + h / 2.0, w / 2.0, h / 2.0, leftEdge, middle, botLeft, botEdge);	// bot left quad
	divideSquare(false, x + w / 2.0, y + h / 2.0, w / 2.0, h / 2.0, middle, rightEdge, botEdge, botRight);	// bot right quad
}
<|endoftext|>


<commit_before>#include "fs_options.h"
#include "fs_meta_ops.h"
#include "file_meta_ops.h"
#include "dir_meta_ops.h"
#include "fs_logger.h"

#include <unistd.h>
#include <iostream>
#include <fuse.h>

using namespace mgridfs;

namespace mgridfs {
	FSOptions globalFSOptions;
}

namespace {
	struct fuse_operations mgridfsOps = {};
}

int main(int argc, char* argv[], char* arge[]) {
	std::cout << "MongoDB-GridFS" << std::endl;

	mgridfsOps.init = mgridfs::mgridfs_init;
	mgridfsOps.destroy = mgridfs::mgridfs_destroy;

	mgridfsOps.getattr = mgridfs::mgridfs_getattr;
	mgridfsOps.readlink = mgridfs::mgridfs_readlink;
	mgridfsOps.mknod = mgridfs::mgridfs_mknod;

	mgridfsOps.mkdir = mgridfs::mgridfs_mkdir;
	mgridfsOps.rmdir = mgridfs::mgridfs_rmdir;
	mgridfsOps.opendir = mgridfs::mgridfs_opendir;
	mgridfsOps.readdir = mgridfs::mgridfs_readdir;
	mgridfsOps.releasedir = mgridfs::mgridfs_releasedir;
	mgridfsOps.fsyncdir = mgridfs::mgridfs_fsyncdir;

	mgridfsOps.unlink = mgridfs::mgridfs_unlink;
	mgridfsOps.symlink = mgridfs::mgridfs_symlink;
	mgridfsOps.rename = mgridfs::mgridfs_rename;
	mgridfsOps.link = mgridfs::mgridfs_link;
	mgridfsOps.chmod = mgridfs::mgridfs_chmod;
	mgridfsOps.chown = mgridfs::mgridfs_chown;
	mgridfsOps.truncate = mgridfs::mgridfs_truncate;
	mgridfsOps.utime = mgridfs::mgridfs_utime;
	mgridfsOps.open = mgridfs::mgridfs_open;
	mgridfsOps.read = mgridfs::mgridfs_read;
	mgridfsOps.write = mgridfs::mgridfs_write;
	mgridfsOps.statfs = mgridfs::mgridfs_statfs;
	mgridfsOps.flush = mgridfs::mgridfs_flush;
	mgridfsOps.release = mgridfs::mgridfs_release;
	mgridfsOps.fsync = mgridfs::mgridfs_fsync;
	mgridfsOps.setxattr = mgridfs::mgridfs_setxattr;
	mgridfsOps.getxattr = mgridfs::mgridfs_getxattr;
	mgridfsOps.listxattr = mgridfs::mgridfs_listxattr;
	mgridfsOps.removexattr = mgridfs::mgridfs_removexattr;
	mgridfsOps.create = mgridfs::mgridfs_create;
	mgridfsOps.ftruncate = mgridfs::mgridfs_ftruncate;
	mgridfsOps.fgetattr = mgridfs::mgridfs_fgetattr;
	mgridfsOps.lock = mgridfs::mgridfs_lock;
	mgridfsOps.utimens = mgridfs::mgridfs_utimens;
	mgridfsOps.bmap = mgridfs::mgridfs_bmap;
	mgridfsOps.ioctl = mgridfs::mgridfs_ioctl;
	mgridfsOps.poll = mgridfs::mgridfs_poll;
	mgridfsOps.write_buf = mgridfs::mgridfs_write_buf;
	mgridfsOps.read_buf = mgridfs::mgridfs_read_buf;
	mgridfsOps.flock = mgridfs::mgridfs_flock;
	mgridfsOps.fallocate = mgridfs::mgridfs_fallocate;

	struct fuse_args fuseArgs = FUSE_ARGS_INIT(argc, argv);
	if (!mgridfs::globalFSOptions.fromCommandLine(fuseArgs)) {
		std::cerr << "ERROR: Failed to parse options passed to program, will not mount file system" << std::endl;
		return 1;
	}

	fuse_main(fuseArgs.argc, fuseArgs.argv, &mgridfsOps, NULL);
	return 0;
}
<commit_msg>Reorganized the function call assignments into appropriate grouping<commit_after>#include "fs_options.h"
#include "fs_meta_ops.h"
#include "file_meta_ops.h"
#include "dir_meta_ops.h"
#include "fs_logger.h"

#include <unistd.h>
#include <iostream>
#include <fuse.h>

using namespace mgridfs;

namespace mgridfs {
	FSOptions globalFSOptions;
}

namespace {
	struct fuse_operations mgridfsOps = {};
}

int main(int argc, char* argv[], char* arge[]) {
	std::cout << "MongoDB-GridFS" << std::endl;

	// File-system meta / setup / cleanup functions
	mgridfsOps.init = mgridfs::mgridfs_init;
	mgridfsOps.destroy = mgridfs::mgridfs_destroy;
	mgridfsOps.statfs = mgridfs::mgridfs_statfs;

	// File/Directory attribute management functionality
	mgridfsOps.getattr = mgridfs::mgridfs_getattr;
	mgridfsOps.fgetattr = mgridfs::mgridfs_fgetattr;
	mgridfsOps.access = NULL; // optional, un-implemented functionality
	mgridfsOps.setxattr = mgridfs::mgridfs_setxattr;
	mgridfsOps.getxattr = mgridfs::mgridfs_getxattr;
	mgridfsOps.listxattr = mgridfs::mgridfs_listxattr;
	mgridfsOps.removexattr = mgridfs::mgridfs_removexattr;
	mgridfsOps.chmod = mgridfs::mgridfs_chmod;
	mgridfsOps.chown = mgridfs::mgridfs_chown;
	mgridfsOps.utime = mgridfs::mgridfs_utime;
	mgridfsOps.utimens = mgridfs::mgridfs_utimens;

	mgridfsOps.mknod = mgridfs::mgridfs_mknod;

	// Directory functionality
	mgridfsOps.mkdir = mgridfs::mgridfs_mkdir;
	mgridfsOps.rmdir = mgridfs::mgridfs_rmdir;
	mgridfsOps.opendir = mgridfs::mgridfs_opendir;
	mgridfsOps.readdir = mgridfs::mgridfs_readdir;
	mgridfsOps.releasedir = mgridfs::mgridfs_releasedir;
	mgridfsOps.fsyncdir = mgridfs::mgridfs_fsyncdir;

	// File linking functionality functions
	mgridfsOps.link = NULL; // Hard-links are not supported
	mgridfsOps.readlink = mgridfs::mgridfs_readlink;
	mgridfsOps.unlink = mgridfs::mgridfs_unlink;
	mgridfsOps.symlink = mgridfs::mgridfs_symlink;

	// Normal file related operations
	mgridfsOps.rename = mgridfs::mgridfs_rename;
	mgridfsOps.truncate = mgridfs::mgridfs_truncate;
	mgridfsOps.ftruncate = mgridfs::mgridfs_ftruncate;
	mgridfsOps.open = mgridfs::mgridfs_open;
	mgridfsOps.read = mgridfs::mgridfs_read;
	mgridfsOps.write = mgridfs::mgridfs_write;
	mgridfsOps.flush = mgridfs::mgridfs_flush;
	mgridfsOps.release = mgridfs::mgridfs_release;
	mgridfsOps.fsync = mgridfs::mgridfs_fsync;
	mgridfsOps.create = mgridfs::mgridfs_create;
	mgridfsOps.lock = mgridfs::mgridfs_lock;
	mgridfsOps.bmap = mgridfs::mgridfs_bmap;
	mgridfsOps.ioctl = mgridfs::mgridfs_ioctl;
	mgridfsOps.poll = mgridfs::mgridfs_poll;
	mgridfsOps.write_buf = mgridfs::mgridfs_write_buf;
	mgridfsOps.read_buf = mgridfs::mgridfs_read_buf;
	mgridfsOps.flock = mgridfs::mgridfs_flock;
	mgridfsOps.fallocate = mgridfs::mgridfs_fallocate;

	struct fuse_args fuseArgs = FUSE_ARGS_INIT(argc, argv);
	if (!mgridfs::globalFSOptions.fromCommandLine(fuseArgs)) {
		std::cerr << "ERROR: Failed to parse options passed to program, will not mount file system" << std::endl;
		return 1;
	}

	fuse_main(fuseArgs.argc, fuseArgs.argv, &mgridfsOps, NULL);
	return 0;
}
<|endoftext|>


<commit_before>//
//  scheduler_object.cpp
//  fibio
//
//  Created by Chen Xu on 14-3-5.
//  Copyright (c) 2014 0d0a.com. All rights reserved.
//

#include <fibio/fibers/fiber.hpp>
#include "scheduler_object.hpp"

namespace fibio { namespace fibers { namespace detail {
    std::once_flag scheduler_object::instance_inited_;
    std::shared_ptr<scheduler_object> scheduler_object::the_instance_;

    scheduler_object::scheduler_object()
    : fiber_count_(0)
    , started_(false)
    {}

    fiber_ptr_t scheduler_object::make_fiber(std::function<void()> &&entry) {
        std::lock_guard<std::mutex> guard(m_);
        fiber_count_++;
        fiber_ptr_t ret(std::make_shared<fiber_object>(shared_from_this(), std::move(entry)));
        if (!started_) {
            started_=true;
        }
        ret->schedule();
        return ret;
    }

    void scheduler_object::start(size_t nthr) {
        std::lock_guard<std::mutex> guard(m_);
        if (threads_.size()>0) {
            // Already started
            return;
        } else {
            //fiber_count_=0;
        }
        if (!check_timer_) {
            check_timer_=std::make_shared<timer_t>(io_service_);
        }
        check_timer_->expires_from_now(std::chrono::seconds(1));
        scheduler_ptr_t pthis(shared_from_this());
        check_timer_->async_wait([pthis](std::error_code ec){ pthis->on_check_timer(ec); });
        for(size_t i=0; i<nthr; i++) {
            threads_.push_back(std::thread([pthis](){
                pthis->io_service_.run();
            }));
        }
    }

    void scheduler_object::join() {
        for(std::thread &t : threads_) {
            t.join();
        }
    }

    /*
    void scheduler_object::add_thread(size_t nthr) {
        std::lock_guard<std::mutex> guard(m_);
        scheduler_ptr_t pthis(shared_from_this());
        for(size_t i=0; i<nthr; i++) {
            threads_.push_back(std::thread([pthis](){
                pthis->io_service_.run();
            }));
        }
    }
     */

    void scheduler_object::on_fiber_exit() {
        std::lock_guard<std::mutex> guard(m_);
        fiber_count_--;
    }

    void scheduler_object::on_check_timer(std::error_code ec) {
        std::lock_guard<std::mutex> guard(m_);
        if (fiber_count_>0 || !started_) {
            //printf("Active fiber %lu", size_t(fiber_count_));
            check_timer_->expires_from_now(std::chrono::milliseconds(50));
            scheduler_ptr_t pthis(shared_from_this());
            check_timer_->async_wait([pthis](std::error_code ec){ pthis->on_check_timer(ec); });
        } else {
            io_service_.stop();
        }
    }

    std::shared_ptr<scheduler_object> scheduler_object::get_instance() {
        std::call_once(instance_inited_, [](){
            scheduler_object::the_instance_=std::make_shared<scheduler_object>();
        });
        return scheduler_object::the_instance_;
    }
}}} // End of namespace fibio::fibers::detail

namespace fibio { namespace fibers {
    scheduler::scheduler()
    : m_(std::make_shared<detail::scheduler_object>())
    {}

    scheduler::scheduler(std::shared_ptr<detail::scheduler_object> m)
    : m_(m)
    {}

    void scheduler::start(size_t nthr) {
        m_->start(nthr);
    }

    void scheduler::join() {
        m_->join();
    }

    /*
    void scheduler::add_worker_thread(size_t nthr) {
        m_->add_thread(nthr);
    }
     */

    scheduler scheduler::get_instance() {
        return scheduler(detail::scheduler_object::get_instance());
    }
}}  // End of namespace fibio::fibers
<commit_msg>Reset scheduler after joining<commit_after>//
//  scheduler_object.cpp
//  fibio
//
//  Created by Chen Xu on 14-3-5.
//  Copyright (c) 2014 0d0a.com. All rights reserved.
//

#include <fibio/fibers/fiber.hpp>
#include "scheduler_object.hpp"

namespace fibio { namespace fibers { namespace detail {
    std::once_flag scheduler_object::instance_inited_;
    std::shared_ptr<scheduler_object> scheduler_object::the_instance_;

    scheduler_object::scheduler_object()
    : fiber_count_(0)
    , started_(false)
    {}

    fiber_ptr_t scheduler_object::make_fiber(std::function<void()> &&entry) {
        std::lock_guard<std::mutex> guard(m_);
        fiber_count_++;
        fiber_ptr_t ret(std::make_shared<fiber_object>(shared_from_this(), std::move(entry)));
        if (!started_) {
            started_=true;
        }
        ret->schedule();
        return ret;
    }

    void scheduler_object::start(size_t nthr) {
        std::lock_guard<std::mutex> guard(m_);
        if (threads_.size()>0) {
            // Already started
            return;
        } else {
            //fiber_count_=0;
        }
        if (!check_timer_) {
            check_timer_=std::make_shared<timer_t>(io_service_);
        }
        check_timer_->expires_from_now(std::chrono::seconds(1));
        scheduler_ptr_t pthis(shared_from_this());
        check_timer_->async_wait([pthis](std::error_code ec){ pthis->on_check_timer(ec); });
        for(size_t i=0; i<nthr; i++) {
            threads_.push_back(std::thread([pthis](){
                pthis->io_service_.run();
            }));
        }
    }

    void scheduler_object::join() {
        for(std::thread &t : threads_) {
            t.join();
        }
        threads_.clear();
        started_=false;
        io_service_.reset();
    }

    /*
    void scheduler_object::add_thread(size_t nthr) {
        std::lock_guard<std::mutex> guard(m_);
        scheduler_ptr_t pthis(shared_from_this());
        for(size_t i=0; i<nthr; i++) {
            threads_.push_back(std::thread([pthis](){
                pthis->io_service_.run();
            }));
        }
    }
     */

    void scheduler_object::on_fiber_exit() {
        std::lock_guard<std::mutex> guard(m_);
        fiber_count_--;
    }

    void scheduler_object::on_check_timer(std::error_code ec) {
        std::lock_guard<std::mutex> guard(m_);
        if (fiber_count_>0 || !started_) {
            //printf("Active fiber %lu", size_t(fiber_count_));
            check_timer_->expires_from_now(std::chrono::milliseconds(50));
            scheduler_ptr_t pthis(shared_from_this());
            check_timer_->async_wait([pthis](std::error_code ec){ pthis->on_check_timer(ec); });
        } else {
            io_service_.stop();
        }
    }

    std::shared_ptr<scheduler_object> scheduler_object::get_instance() {
        std::call_once(instance_inited_, [](){
            scheduler_object::the_instance_=std::make_shared<scheduler_object>();
        });
        return scheduler_object::the_instance_;
    }
}}} // End of namespace fibio::fibers::detail

namespace fibio { namespace fibers {
    scheduler::scheduler()
    : m_(std::make_shared<detail::scheduler_object>())
    {}

    scheduler::scheduler(std::shared_ptr<detail::scheduler_object> m)
    : m_(m)
    {}

    void scheduler::start(size_t nthr) {
        m_->start(nthr);
    }

    void scheduler::join() {
        m_->join();
    }

    /*
    void scheduler::add_worker_thread(size_t nthr) {
        m_->add_thread(nthr);
    }
     */

    scheduler scheduler::get_instance() {
        return scheduler(detail::scheduler_object::get_instance());
    }
}}  // End of namespace fibio::fibers
<|endoftext|>


<commit_before>// Main.cpp
//============================

//===========================
// Include Dependencies
#include <iostream>
#include <math.h>
#include <string>
#include <vector>
#include <fstream>

#include "phys.h"
#include "coord.h"
//#include "node.h"
#include "cell.h"
#include "tissue.h"
//==============================

using namespace std;

//============================

int main() {

	string init_tissue = "cell_start.txt";
	//make a new cell object

	Tissue growing_Tissue(init_tissue);

	cout << "Finished creating Cell" << endl;
	//parameters for time step
    double numSteps = 40;

	// Variable for dataoutput
	int digits;
	string format = ".vtk";
	string Number;
	string initial = "Animation/Plant_Cell_";
	string Filename;
	ofstream ofs;
	int out = 0; //counter for creating output/vtk files

	//loop for time steps
	for(int Ti = 0; Ti*dt < numSteps; Ti++) {
		//loop through all cells
		//for now only one cell

		//Print to dataOutput and VTK files

		if (Ti % 250 == 0) {

			digits = ceil(log10(out + 1));
			if (digits == 1 || digits == 0) {
				Number = "0000" + to_string(out);
			}
			else if (digits == 2) {
				Number = "000" + to_string(out);
			}
			else if (digits == 3) {
				Number = "00" + to_string(out);
			}
			else if (digits == 4) {
				Number = "0" + to_string(out);
			}

			Filename = initial + Number + format;

			ofs.open(Filename.c_str());
			growing_Tissue.print_VTK_File(ofs);
			ofs.close();

			out++;
		}

		if (Ti % 1000 == 0) {
			cout << "Simulation still running. Ti: " << Ti << endl;
		}

		//New Tissue GRowth
		growing_Tissue.grow_Cells(Ti);
		//Calculate new forces on cells and nodes
		growing_Tissue.calc_New_Forces();
		//Update node positions
		growing_Tissue.update_Cell_Locations();

	}

	return 0;
}

<commit_msg>setup for timing<commit_after>// Main.cpp
//============================

//===========================
// Include Dependencies
#include <iostream>
#include <math.h>
#include <string>
#include <vector>
#include <fstream>
#include <ctime>

#include "phys.h"
#include "coord.h"
//#include "node.h"
#include "cell.h"
#include "tissue.h"
//==============================

using namespace std;

//============================

int main() {

	int start = clock();

	string init_tissue = "cell_start.txt";
	//make a new cell object

	Tissue growing_Tissue(init_tissue);

	cout << "Finished creating Cell" << endl;
	//parameters for time step
    double numSteps = 20;

	// Variable for dataoutput
	int digits;
	string format = ".vtk";
	string Number;
	string initial = "Animation/Plant_Cell_";
	string Filename;
	ofstream ofs;
	int out = 0; //counter for creating output/vtk files

	//loop for time steps
	for(int Ti = 0; Ti*dt < numSteps; Ti++) {
		//loop through all cells
		//for now only one cell

		//Print to dataOutput and VTK files

		if (Ti % 250 == 0) {

			digits = ceil(log10(out + 1));
			if (digits == 1 || digits == 0) {
				Number = "0000" + to_string(out);
			}
			else if (digits == 2) {
				Number = "000" + to_string(out);
			}
			else if (digits == 3) {
				Number = "00" + to_string(out);
			}
			else if (digits == 4) {
				Number = "0" + to_string(out);
			}

			Filename = initial + Number + format;

			ofs.open(Filename.c_str());
			growing_Tissue.print_VTK_File(ofs);
			ofs.close();

			out++;
		}

		if (Ti % 1000 == 0) {
			cout << "Simulation still running. Ti: " << Ti << endl;
		}

		//New Tissue GRowth
		growing_Tissue.grow_Cells(Ti);
		//Calculate new forces on cells and nodes
		growing_Tissue.calc_New_Forces();
		//Update node positions
		growing_Tissue.update_Cell_Locations();

	}

	int stop = clock();

	cout << "Time: " << (stop - start) / double(CLOCKS_PER_SEC) * 1000 << endl;

	return 0;
}

<|endoftext|>


<commit_before>0c718d5c-2748-11e6-bc80-e0f84713e7b8<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>0c7d205e-2748-11e6-bc2c-e0f84713e7b8<|endoftext|>


<commit_before>/**
* Released under the same permissive MIT-license as Urho3D.
* https://raw.githubusercontent.com/urho3d/Urho3D/master/License.txt
*/

#include <string>
#include <memory>
#include <fstream>
#include <sstream>

#include <Urho3D/Urho3D.h>
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Graphics/RenderPath.h>
#include <Urho3D/Engine/Application.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Input/InputEvents.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/XMLFile.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/UI/Button.h>
#include <Urho3D/UI/UIEvents.h>
#include <Urho3D/UI/Window.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Scene/SceneEvents.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/Geometry.h>
#include <Urho3D/Graphics/Renderer.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Graphics/Light.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Graphics/Material.h>
#include <Urho3D/Graphics/Skybox.h>
#include <Urho3D/Graphics/Zone.h>
#include <Urho3D/Audio/Sound.h>
#include <Urho3D/Audio/SoundSource3D.h>
#include <Urho3D/Audio/SoundListener.h>
#include <Urho3D/Audio/Audio.h>
#include <Urho3D/Graphics/ParticleEmitter.h>
#include <Urho3D/Graphics/ParticleEffect.h>
#include <Urho3D/Graphics/Terrain.h>

using namespace Urho3D;

/// \brief Calls SetModel on the given model and tries to load the model file and all texture files mentioned in a model_name+".txt".
/// model_name is supposed to have no file extension. Example: "Data/Models/Box", loads the model "Data/Models/Box.mdl".
/// It's a template to support all model classes like AnimatedModel and StaticModel.
template<typename T>
void set_model(T* model,Urho3D::ResourceCache* cache,std::string model_name)
{
    std::string filename_model=model_name;
    model->SetModel(cache->GetResource<Urho3D::Model>(Urho3D::String(filename_model.append(".mdl").c_str())));
    std::string filename_txt=model_name;
    filename_txt.append(".txt");
    std::ifstream file(filename_txt.c_str());
    std::string line;
    if(file.is_open())
        for(int i=0;getline(file,line);i++)
            model->SetMaterial(i,cache->GetResource<Urho3D::Material>(Urho3D::String(line.c_str())));
}

/// SampleApplication main class mainly used for setup. The control is then given to the game states (starting with gs_main_menu).
class SampleApplication : public Application
{
public:
    SharedPtr<Scene> scene_;
    Node* cameraNode_;
    SharedPtr<Urho3D::Node> node_rotating_planet;
    Urho3D::Text* window_text;
    SharedPtr<Urho3D::Window> window;
    Urho3D::Terrain* terrain;
    Urho3D::Camera* camera_;
    SharedPtr<Node> skyNode;
    SharedPtr<Node> node_torch;
    SharedPtr<Node> lightNode;

    SampleApplication(Context * context) : Application(context) {}

    virtual void Setup()
    {
        engineParameters_["FullScreen"]=false;
        engineParameters_["WindowWidth"]=1280;
        engineParameters_["WindowHeight"]=720;
        engineParameters_["WindowResizable"]=true;
        //engineParameters_["Multisample"]=16;
    }

    virtual void Start()
    {
        ResourceCache* cache=GetSubsystem<ResourceCache>();
        GetSubsystem<UI>()->GetRoot()->SetDefaultStyle(cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));

        scene_=new Scene(context_);
        scene_->CreateComponent<Octree>();
        scene_->CreateComponent<DebugRenderer>();

        cameraNode_=scene_->CreateChild("Camera");
        camera_=cameraNode_->CreateComponent<Camera>();
        camera_->SetFarClip(50000);
        camera_->SetNearClip(0.01);
        camera_->SetFov(75);
        SoundListener* listener=cameraNode_->CreateComponent<SoundListener>();
        GetSubsystem<Audio>()->SetListener(listener);
        GetSubsystem<Audio>()->SetMasterGain(SOUND_MUSIC,0.3);

        Renderer* renderer=GetSubsystem<Renderer>();
        SharedPtr<Viewport> viewport(new Viewport(context_,scene_,cameraNode_->GetComponent<Camera>()));
        renderer->SetViewport(0,viewport);
        renderer->SetShadowMapSize(1024);
        renderer->SetHDRRendering(true);

        RenderPath* effectRenderPath=viewport->GetRenderPath();
        effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/AutoExposure.xml"));
        //effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/BloomHDR.xml"));
        effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/BloomHDR_stronger.xml"));
        effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/FXAA2.xml"));

        Node* zoneNode=scene_->CreateChild("Zone");
        Zone* zone=zoneNode->CreateComponent<Zone>();
        zone->SetBoundingBox(BoundingBox(-50000.0f,50000.0f));
        zone->SetFogStart(100000.0f);
        zone->SetFogEnd(200000.0f);
        zone->SetAmbientColor(Color(0.1,0.1,0.1));

        SubscribeToEvent(E_KEYDOWN,URHO3D_HANDLER(SampleApplication,HandleKeyDown));
        SubscribeToEvent(E_UPDATE,URHO3D_HANDLER(SampleApplication,HandleUpdate));

        cameraNode_->SetPosition(Vector3(0,0,0));
        cameraNode_->SetDirection(Vector3::FORWARD);

        // create a transparent window with some text to display things like help and FPS
        {
            window=new Window(context_);
            GetSubsystem<UI>()->GetRoot()->AddChild(window);
            window->SetStyle("Window");
            window->SetSize(600,70);
            window->SetColor(Color(.0,.15,.3,.5));
            window->SetAlignment(HA_LEFT,VA_TOP);

            window_text=new Text(context_);
            window_text->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"),14);
            window_text->SetColor(Color(.8,.85,.9));
            window_text->SetAlignment(HA_LEFT,VA_TOP);
            window->AddChild(window_text);
        }

        // a rotating planet
        {
            node_rotating_planet=scene_->CreateChild("Planet");
            node_rotating_planet->SetPosition(Vector3(-4,1.6,6));
            node_rotating_planet->Scale(2);
            StaticModel* boxObject=node_rotating_planet->CreateComponent<StaticModel>();
            boxObject->SetModel(cache->GetResource<Model>("Models/planet.mdl"));
            boxObject->SetMaterial(cache->GetResource<Material>("Materials/planet_dsn.xml"));
            boxObject->SetCastShadows(true);
        }

        // skybox
        {
            skyNode=scene_->CreateChild("Sky");
            skyNode->SetScale(1500.0f);
            Skybox* skybox=skyNode->CreateComponent<Skybox>();
            skybox->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
            skybox->SetMaterial(cache->GetResource<Material>("Materials/Skybox.xml"));
        }

        // a torch with a light, sound and particle effects
        {
            node_torch=scene_->CreateChild("Light");
            Vector3 pos(Vector3(3,-0.5,6));
            node_torch->SetPosition(pos);

            StaticModel* boxObject=node_torch->CreateComponent<StaticModel>();
            set_model(boxObject,cache,"Data/Models/torch");
            boxObject->SetCastShadows(true);
            boxObject->SetOccludee(true);
            boxObject->SetShadowDistance(200);
            boxObject->SetDrawDistance(200);

            Node* lightNode=node_torch->CreateChild();
            lightNode->Translate(Vector3(0,2,0));
            Light* light=lightNode->CreateComponent<Light>();
            light->SetLightType(LIGHT_POINT);
            light->SetRange(50);
            light->SetBrightness(1.2);
            light->SetColor(Color(1.0,0.6,0.3,1.0));
            light->SetCastShadows(true);
            light->SetShadowDistance(200);
            light->SetDrawDistance(200);

            Node* n_particle=node_torch->CreateChild();
            n_particle->Translate(Vector3(0,1.6,0));
            ParticleEmitter* emitter=n_particle->CreateComponent<ParticleEmitter>();
            emitter->SetEffect(cache->GetResource<ParticleEffect>("Particle/torch_fire.xml"));
            emitter=n_particle->CreateComponent<ParticleEmitter>();
            emitter->SetEffect(cache->GetResource<ParticleEffect>("Particle/torch_smoke.xml"));

            Sound* sound_torch=cache->GetResource<Sound>("Sounds/torch.ogg");
            sound_torch->SetLooped(true);
            SoundSource3D* sound_torch_source=n_particle->CreateComponent<SoundSource3D>();
            sound_torch_source->SetNearDistance(1);
            sound_torch_source->SetFarDistance(50);
            sound_torch_source->SetSoundType(SOUND_EFFECT);
            sound_torch_source->Play(sound_torch);
        }

        // sun
        {
            lightNode=scene_->CreateChild("Light");
            Light* light=lightNode->CreateComponent<Light>();
            light->SetLightType(LIGHT_DIRECTIONAL);
            light->SetCastShadows(true);
            light->SetShadowBias(BiasParameters(0.00000025f,0.1f));
            light->SetShadowCascade(CascadeParameters(20.0f,60.0f,180.0f,560.0f,100.0f,100.0f));
            light->SetShadowResolution(1.0);
            light->SetBrightness(1.0);
            light->SetColor(Color(1.0,0.9,0.8,1));
            lightNode->SetDirection(Vector3::FORWARD);
            lightNode->Yaw(-150);   // horizontal
            lightNode->Pitch(30);   // vertical
            lightNode->Translate(Vector3(0,0,-20000));

            BillboardSet* billboardObject=lightNode->CreateComponent<BillboardSet>();
            billboardObject->SetNumBillboards(1);
            billboardObject->SetMaterial(cache->GetResource<Material>("Materials/sun.xml"));
            billboardObject->SetSorted(true);
            Billboard* bb=billboardObject->GetBillboard(0);
            bb->size_=Vector2(10000,10000);
            bb->rotation_=Random()*360.0f;
            bb->enabled_=true;
            billboardObject->Commit();
        }

        {
            Node* terrainNode=scene_->CreateChild("Terrain");
            terrainNode->SetPosition(Vector3(3.0f,-0.4f));
            terrain=terrainNode->CreateComponent<Terrain>();
            terrain->SetPatchSize(128);
            terrain->SetSpacing(Vector3(2,0.5,2));
            terrain->SetSmoothing(true);
            terrain->SetHeightMap(cache->GetResource<Image>("Textures/HeightMap.png"));
            terrain->SetMaterial(cache->GetResource<Material>("Materials/Terrain.xml"));
            terrain->SetCastShadows(true);
            terrain->SetOccluder(true);
        }
    }

    virtual void Stop()
    {
    }

    void HandleUpdate(StringHash eventType,VariantMap& eventData)
    {
        float timeStep=eventData[Update::P_TIMESTEP].GetFloat();

        std::string str="WASD, mouse and shift to move. T to toggle fill mode,\nG to toggle GUI, Tab to toggle mouse mode, Esc to quit.\n";
        {
            std::ostringstream ss;
            ss<<1/timeStep;
            std::string s(ss.str());
            str.append(s.substr(0,6));
        }
        str.append(" FPS ");
        String s(str.c_str(),str.size());
        window_text->SetText(s);

        node_rotating_planet->Rotate(Quaternion(0,-22*timeStep,0));

        // Movement speed as world units per second
        float MOVE_SPEED=10.0f;
        // Mouse sensitivity as degrees per pixel
        const float MOUSE_SENSITIVITY=0.1f;

        // camera movement
        Input* input=GetSubsystem<Input>();
        if(input->GetQualifierDown(1))  // 1 is shift, 2 is ctrl, 4 is alt
            MOVE_SPEED*=10;
        if(input->GetKeyDown('W'))
            cameraNode_->Translate(Vector3(0,0, 1)*MOVE_SPEED*timeStep);
        if(input->GetKeyDown('S'))
            cameraNode_->Translate(Vector3(0,0,-1)*MOVE_SPEED*timeStep);
        if(input->GetKeyDown('A'))
            cameraNode_->Translate(Vector3(-1,0,0)*MOVE_SPEED*timeStep);
        if(input->GetKeyDown('D'))
            cameraNode_->Translate(Vector3( 1,0,0)*MOVE_SPEED*timeStep);

        if(!GetSubsystem<Input>()->IsMouseVisible())
        {
            IntVector2 mouseMove=input->GetMouseMove();
            if(mouseMove.x_>-2000000000&&mouseMove.y_>-2000000000)
            {
                static float yaw_=0;
                static float pitch_=0;
                yaw_+=MOUSE_SENSITIVITY*mouseMove.x_;
                pitch_+=MOUSE_SENSITIVITY*mouseMove.y_;
                pitch_=Clamp(pitch_,-90.0f,90.0f);
                // Reset rotation and set yaw and pitch again
                cameraNode_->SetDirection(Vector3::FORWARD);
                cameraNode_->Yaw(yaw_);
                cameraNode_->Pitch(pitch_);
            }
        }
    }

    void HandleKeyDown(StringHash eventType,VariantMap& eventData)
    {
        using namespace KeyDown;
        int key=eventData[P_KEY].GetInt();

        if(key==KEY_TAB)
        {
            GetSubsystem<Input>()->SetMouseVisible(!GetSubsystem<Input>()->IsMouseVisible());
            GetSubsystem<Input>()->SetMouseGrabbed(!GetSubsystem<Input>()->IsMouseGrabbed());
        }
        else if(key==KEY_ESC)
            engine_->Exit();
        else if(key==KEY_G)
            window_text->SetVisible(!window_text->IsVisible());
        else if(key==KEY_T)
            camera_->SetFillMode(camera_->GetFillMode()==FILL_WIREFRAME?FILL_SOLID:FILL_WIREFRAME);
    }
};

URHO3D_DEFINE_APPLICATION_MAIN(SampleApplication)
<commit_msg>Fixed shadow stripe issue in DX11 and torch position.<commit_after>/**
* Released under the same permissive MIT-license as Urho3D.
* https://raw.githubusercontent.com/urho3d/Urho3D/master/License.txt
*/

#include <string>
#include <memory>
#include <fstream>
#include <sstream>

#include <Urho3D/Urho3D.h>
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Graphics/RenderPath.h>
#include <Urho3D/Engine/Application.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/Input/InputEvents.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Resource/XMLFile.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/UI/Button.h>
#include <Urho3D/UI/UIEvents.h>
#include <Urho3D/UI/Window.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Scene/SceneEvents.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/Geometry.h>
#include <Urho3D/Graphics/Renderer.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Graphics/Light.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/Graphics/StaticModel.h>
#include <Urho3D/Graphics/Material.h>
#include <Urho3D/Graphics/Skybox.h>
#include <Urho3D/Graphics/Zone.h>
#include <Urho3D/Audio/Sound.h>
#include <Urho3D/Audio/SoundSource3D.h>
#include <Urho3D/Audio/SoundListener.h>
#include <Urho3D/Audio/Audio.h>
#include <Urho3D/Graphics/ParticleEmitter.h>
#include <Urho3D/Graphics/ParticleEffect.h>
#include <Urho3D/Graphics/Terrain.h>

using namespace Urho3D;

/// \brief Calls SetModel on the given model and tries to load the model file and all texture files mentioned in a model_name+".txt".
/// model_name is supposed to have no file extension. Example: "Data/Models/Box", loads the model "Data/Models/Box.mdl".
/// It's a template to support all model classes like AnimatedModel and StaticModel.
template<typename T>
void set_model(T* model,Urho3D::ResourceCache* cache,std::string model_name)
{
    std::string filename_model=model_name;
    model->SetModel(cache->GetResource<Urho3D::Model>(Urho3D::String(filename_model.append(".mdl").c_str())));
    std::string filename_txt=model_name;
    filename_txt.append(".txt");
    std::ifstream file(filename_txt.c_str());
    std::string line;
    if(file.is_open())
        for(int i=0;getline(file,line);i++)
            model->SetMaterial(i,cache->GetResource<Urho3D::Material>(Urho3D::String(line.c_str())));
}

/// SampleApplication main class mainly used for setup. The control is then given to the game states (starting with gs_main_menu).
class SampleApplication : public Application
{
public:
    SharedPtr<Scene> scene_;
    Node* cameraNode_;
    SharedPtr<Urho3D::Node> node_rotating_planet;
    Urho3D::Text* window_text;
    SharedPtr<Urho3D::Window> window;
    Urho3D::Terrain* terrain;
    Urho3D::Camera* camera_;
    SharedPtr<Node> skyNode;
    SharedPtr<Node> node_torch;
    SharedPtr<Node> lightNode;

    SampleApplication(Context * context) : Application(context) {}

    virtual void Setup()
    {
        engineParameters_["FullScreen"]=false;
        engineParameters_["WindowWidth"]=1280;
        engineParameters_["WindowHeight"]=720;
        engineParameters_["WindowResizable"]=true;
        //engineParameters_["Multisample"]=16;
    }

    virtual void Start()
    {
        ResourceCache* cache=GetSubsystem<ResourceCache>();
        GetSubsystem<UI>()->GetRoot()->SetDefaultStyle(cache->GetResource<XMLFile>("UI/DefaultStyle.xml"));

        scene_=new Scene(context_);
        scene_->CreateComponent<Octree>();
        scene_->CreateComponent<DebugRenderer>();

        cameraNode_=scene_->CreateChild("Camera");
        camera_=cameraNode_->CreateComponent<Camera>();
        camera_->SetFarClip(50000);
        camera_->SetNearClip(0.01);
        camera_->SetFov(75);
        SoundListener* listener=cameraNode_->CreateComponent<SoundListener>();
        GetSubsystem<Audio>()->SetListener(listener);
        GetSubsystem<Audio>()->SetMasterGain(SOUND_MUSIC,0.3);

        Renderer* renderer=GetSubsystem<Renderer>();
        SharedPtr<Viewport> viewport(new Viewport(context_,scene_,cameraNode_->GetComponent<Camera>()));
        renderer->SetViewport(0,viewport);
        renderer->SetShadowMapSize(1024);
        renderer->SetHDRRendering(true);

        RenderPath* effectRenderPath=viewport->GetRenderPath();
        effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/AutoExposure.xml"));
        //effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/BloomHDR.xml"));
        effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/BloomHDR_stronger.xml"));
        effectRenderPath->Append(cache->GetResource<XMLFile>("PostProcess/FXAA2.xml"));

        Node* zoneNode=scene_->CreateChild("Zone");
        Zone* zone=zoneNode->CreateComponent<Zone>();
        zone->SetBoundingBox(BoundingBox(-50000.0f,50000.0f));
        zone->SetFogStart(100000.0f);
        zone->SetFogEnd(200000.0f);
        zone->SetAmbientColor(Color(0.1,0.1,0.1));

        SubscribeToEvent(E_KEYDOWN,URHO3D_HANDLER(SampleApplication,HandleKeyDown));
        SubscribeToEvent(E_UPDATE,URHO3D_HANDLER(SampleApplication,HandleUpdate));

        cameraNode_->SetPosition(Vector3(0,0,0));
        cameraNode_->SetDirection(Vector3::FORWARD);

        // create a transparent window with some text to display things like help and FPS
        {
            window=new Window(context_);
            GetSubsystem<UI>()->GetRoot()->AddChild(window);
            window->SetStyle("Window");
            window->SetSize(600,70);
            window->SetColor(Color(.0,.15,.3,.5));
            window->SetAlignment(HA_LEFT,VA_TOP);

            window_text=new Text(context_);
            window_text->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"),14);
            window_text->SetColor(Color(.8,.85,.9));
            window_text->SetAlignment(HA_LEFT,VA_TOP);
            window->AddChild(window_text);
        }

        // a rotating planet
        {
            node_rotating_planet=scene_->CreateChild("Planet");
            node_rotating_planet->SetPosition(Vector3(-4,1.6,6));
            node_rotating_planet->Scale(2);
            StaticModel* boxObject=node_rotating_planet->CreateComponent<StaticModel>();
            boxObject->SetModel(cache->GetResource<Model>("Models/planet.mdl"));
            boxObject->SetMaterial(cache->GetResource<Material>("Materials/planet_dsn.xml"));
            boxObject->SetCastShadows(true);
        }

        // skybox
        {
            skyNode=scene_->CreateChild("Sky");
            skyNode->SetScale(1500.0f);
            Skybox* skybox=skyNode->CreateComponent<Skybox>();
            skybox->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
            skybox->SetMaterial(cache->GetResource<Material>("Materials/Skybox.xml"));
        }

        // a torch with a light, sound and particle effects
        {
            node_torch=scene_->CreateChild("Torch");
            Vector3 pos(Vector3(3,-0.3,6));
            node_torch->SetPosition(pos);

            StaticModel* boxObject=node_torch->CreateComponent<StaticModel>();
            set_model(boxObject,cache,"Data/Models/torch");
            boxObject->SetCastShadows(true);
            boxObject->SetOccludee(true);
            boxObject->SetShadowDistance(200);
            boxObject->SetDrawDistance(200);

            Node* lightNode=node_torch->CreateChild();
            lightNode->Translate(Vector3(0,2,0));
            Light* light=lightNode->CreateComponent<Light>();
            light->SetLightType(LIGHT_POINT);
            light->SetRange(50);
            light->SetBrightness(1.2);
            light->SetColor(Color(1.0,0.6,0.3,1.0));
            light->SetCastShadows(true);
            light->SetShadowDistance(200);
            light->SetDrawDistance(200);

            Node* n_particle=node_torch->CreateChild();
            n_particle->Translate(Vector3(0,1.6,0));
            ParticleEmitter* emitter=n_particle->CreateComponent<ParticleEmitter>();
            emitter->SetEffect(cache->GetResource<ParticleEffect>("Particle/torch_fire.xml"));
            emitter=n_particle->CreateComponent<ParticleEmitter>();
            emitter->SetEffect(cache->GetResource<ParticleEffect>("Particle/torch_smoke.xml"));

            Sound* sound_torch=cache->GetResource<Sound>("Sounds/torch.ogg");
            sound_torch->SetLooped(true);
            SoundSource3D* sound_torch_source=n_particle->CreateComponent<SoundSource3D>();
            sound_torch_source->SetNearDistance(1);
            sound_torch_source->SetFarDistance(50);
            sound_torch_source->SetSoundType(SOUND_EFFECT);
            sound_torch_source->Play(sound_torch);
        }

        // sun
        {
            lightNode=scene_->CreateChild("Light");
            Light* light=lightNode->CreateComponent<Light>();
            light->SetLightType(LIGHT_DIRECTIONAL);
            light->SetCastShadows(true);
            light->SetShadowBias(BiasParameters(0.00002f,0.5f));
            light->SetShadowCascade(CascadeParameters(10.0f,50.0f,200.0f,400.0f,0.8f));
            light->SetShadowResolution(1.0);
            light->SetBrightness(1.0);
            light->SetColor(Color(1.0,0.9,0.8,1));
            lightNode->SetDirection(Vector3::FORWARD);
            lightNode->Yaw(-150);   // horizontal
            lightNode->Pitch(30);   // vertical
            lightNode->Translate(Vector3(0,0,-20000));

            BillboardSet* billboardObject=lightNode->CreateComponent<BillboardSet>();
            billboardObject->SetNumBillboards(1);
            billboardObject->SetMaterial(cache->GetResource<Material>("Materials/sun.xml"));
            billboardObject->SetSorted(true);
            Billboard* bb=billboardObject->GetBillboard(0);
            bb->size_=Vector2(10000,10000);
            bb->rotation_=Random()*360.0f;
            bb->enabled_=true;
            billboardObject->Commit();
        }

        {
            Node* terrainNode=scene_->CreateChild("Terrain");
            terrainNode->SetPosition(Vector3(3.0f,-0.4f));
            terrain=terrainNode->CreateComponent<Terrain>();
            terrain->SetPatchSize(128);
            terrain->SetSpacing(Vector3(2,0.5,2));
            terrain->SetSmoothing(true);
            terrain->SetHeightMap(cache->GetResource<Image>("Textures/HeightMap.png"));
            terrain->SetMaterial(cache->GetResource<Material>("Materials/Terrain.xml"));
            terrain->SetCastShadows(true);
            terrain->SetOccluder(true);
        }
    }

    virtual void Stop()
    {
    }

    void HandleUpdate(StringHash eventType,VariantMap& eventData)
    {
        float timeStep=eventData[Update::P_TIMESTEP].GetFloat();

        std::string str="WASD, mouse and shift to move. T to toggle fill mode,\nG to toggle GUI, Tab to toggle mouse mode, Esc to quit.\n";
        {
            std::ostringstream ss;
            ss<<1/timeStep;
            std::string s(ss.str());
            str.append(s.substr(0,6));
        }
        str.append(" FPS ");
        String s(str.c_str(),str.size());
        window_text->SetText(s);

        node_rotating_planet->Rotate(Quaternion(0,-22*timeStep,0));

        // Movement speed as world units per second
        float MOVE_SPEED=10.0f;
        // Mouse sensitivity as degrees per pixel
        const float MOUSE_SENSITIVITY=0.1f;

        // camera movement
        Input* input=GetSubsystem<Input>();
        if(input->GetQualifierDown(1))  // 1 is shift, 2 is ctrl, 4 is alt
            MOVE_SPEED*=10;
        if(input->GetKeyDown('W'))
            cameraNode_->Translate(Vector3(0,0, 1)*MOVE_SPEED*timeStep);
        if(input->GetKeyDown('S'))
            cameraNode_->Translate(Vector3(0,0,-1)*MOVE_SPEED*timeStep);
        if(input->GetKeyDown('A'))
            cameraNode_->Translate(Vector3(-1,0,0)*MOVE_SPEED*timeStep);
        if(input->GetKeyDown('D'))
            cameraNode_->Translate(Vector3( 1,0,0)*MOVE_SPEED*timeStep);

        if(!GetSubsystem<Input>()->IsMouseVisible())
        {
            IntVector2 mouseMove=input->GetMouseMove();
            if(mouseMove.x_>-2000000000&&mouseMove.y_>-2000000000)
            {
                static float yaw_=0;
                static float pitch_=0;
                yaw_+=MOUSE_SENSITIVITY*mouseMove.x_;
                pitch_+=MOUSE_SENSITIVITY*mouseMove.y_;
                pitch_=Clamp(pitch_,-90.0f,90.0f);
                // Reset rotation and set yaw and pitch again
                cameraNode_->SetDirection(Vector3::FORWARD);
                cameraNode_->Yaw(yaw_);
                cameraNode_->Pitch(pitch_);
            }
        }
    }

    void HandleKeyDown(StringHash eventType,VariantMap& eventData)
    {
        using namespace KeyDown;
        int key=eventData[P_KEY].GetInt();

        if(key==KEY_TAB)
        {
            GetSubsystem<Input>()->SetMouseVisible(!GetSubsystem<Input>()->IsMouseVisible());
            GetSubsystem<Input>()->SetMouseGrabbed(!GetSubsystem<Input>()->IsMouseGrabbed());
        }
        else if(key==KEY_ESC)
            engine_->Exit();
        else if(key==KEY_G)
            window_text->SetVisible(!window_text->IsVisible());
        else if(key==KEY_T)
            camera_->SetFillMode(camera_->GetFillMode()==FILL_WIREFRAME?FILL_SOLID:FILL_WIREFRAME);
    }
};

URHO3D_DEFINE_APPLICATION_MAIN(SampleApplication)
<|endoftext|>


<commit_before>30ceaf5c-ad5c-11e7-88a7-ac87a332f658<commit_msg>GOD DAMNED IT!<commit_after>31252c26-ad5c-11e7-90fc-ac87a332f658<|endoftext|>


<commit_before>b78af5e8-4b02-11e5-b190-28cfe9171a43<commit_msg>Initial commit.2<commit_after>b79994b8-4b02-11e5-be88-28cfe9171a43<|endoftext|>


<commit_before>b13a01d4-4b02-11e5-9824-28cfe9171a43<commit_msg>fixes, fixes for everyone<commit_after>b148df68-4b02-11e5-a447-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <fstream>

typedef unsigned char byte;
typedef unsigned short word;

struct bitmapHeader
{
	word type;
	word lof;
	word lof2;
	word x_hot;
	word y_hot;
	word first_pixel;
	word first_pixel2;
	word header_size;
	word header_size2;
	word x_size;
	word x_size2;
	word y_size;
	word y_size2;
	word target;
	word bits_per_pixel;
	word compression_method;
	word compression_method2;
	word compressed_size;
	word compressed_size2;
	word x_res;
	word x_res2;
	word y_res;
	word y_res2;
	word used_clrs;
	word used_clrs2;
	word important_clrs;
	word important_clrs2; // 54 bytes
} bitmap;

struct tga_header
{
   int shite;
   int shit1;
   int shit2;
   word xs;
   word ys;
   byte bpp;
   byte magic;
} tga;

bool loadTGA24(const std::string& file)
{
	std::ifstream fin;
	fin.open(file, std::ifstream::binary);

}
<commit_msg>Using sf::Image for img loading. Argument handling done.<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <fstream>

#include <SFML/Graphics/Image.hpp>

typedef unsigned char byte;
typedef unsigned short word;

bool saveHGT(const std::string& file, unsigned hm);

int main(int argc, char** argv)
{
	if(argc != 2 || argc == 3)
	{
		std::cout << "Incorrect # of args, must be 1 (image filename)\n";
		return 1;
	}

	std::string file = argv[1];
	std::string fileName = file.substr(0, file.find_last_of('.'));
	std::string fileExt = file.substr(file.find_last_of('.') + 1);

	// if second arg is given, it is the heightMod, otherwise, make it 0
	unsigned heightMod = argv[2] ? std::stoi(argv[2]) : 0;

	if(!(fileExt == "bmp" || fileExt == "png" || fileExt == "tga" || fileExt == "jpg" || fileExt == "gif" || fileExt == "psd" || fileExt == "hdr" || fileExt == "pic"))
	{
		std::cout << "Unsupported image type: " << fileExt << '\n';
		return 2;
	}

	sf::Image image;
	image.loadFromFile(file);

	bool result = saveHGT(fileName + ".hgt", heightMod);

	if(result)
		std::cout << "HGT successfully created as " << fileName << ".hgt!\n";
	else
	{
		std::cout << "Failed creating HGT.\n";
		return 3;
	}

	return 0;
}

bool saveHGT(const std::string& file, unsigned hm)
{
	std::ofstream fout;

	fout.open(file, std::ofstream::binary);

	return true;
}<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

struct RoomObject
{
}

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
        UNKNOWN,
        GRAVEYARD,
        GRAVEYARD_GATES,
        KHATHARRS_MOMS_HOUSE,
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
	}
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};

struct TheFastcall : public Entity { TheFastcall("The Fastcall", 22); };

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health) {}

    virtual bool act(vector<string> commands) override
    {
        auto& cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
        if(direction=="north"&&map.map_location[map.x][map.y+1]==Map::UNKNOWN)return false;if(direction=="south"&&map.map_location[map.x][map.y-1]==Map::UNKNOWN)return false;if(direction=="east"&&map.map_location[map.x+1][map.y]==Map::UNKNOWN)return false
        ;if(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN)return false;if(direction=="north")map.y++;if(direction=="south")map.y--;if(direction=="east")map.x++;if(direction=="west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(int index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

private:
    vector<shared_ptr<Item>> inventory;
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<commit_msg>BlessedSword<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <memory>
#include <algorithm>
#include <cstring>

using namespace std;

vector<string> split(const string& str) {
    string buf; // Have a buffer string
    stringstream ss(str); // Insert the string into a stream
    vector<string> tokens; // Create vector to hold our words

    while (ss >> buf)
        tokens.push_back(buf);

    return tokens;
}

struct RoomObject
{
}

struct Map
{
	static const int max_width = 100, max_height = 100;
	static const int player_start_x = 50, player_start_y = 50;
    enum Location
    {
        UNKNOWN,
        GRAVEYARD,
        GRAVEYARD_GATES,
        KHATHARRS_MOMS_HOUSE,
    };
	Location map_location[max_width][max_height];
	int x, y;
	Map()
	{
        memset(map_location, UNKNOWN, sizeof(map_location));
		x = 50;
		y = 50;
		map_location[50][50] = GRAVEYARD;
		map_location[50][51] = GRAVEYARD_GATES;
		map_location[50][52] = KHATHARRS_MOMS_HOUSE;
	}
};

struct Entity
{
    Entity(string name, int maxHealth) : name(name), health(maxHealth) {}

    void heal(int points)
    {
        health = min(100, health + points);
        cout << name << " healed to " << health << " health" << endl;
    }

    void damage(int points)
    {
        health = max(0, health - points);
        cout << name << " damaged to " << health << "health" << endl;
    }

    int getHealth() const { return health; }

    // Return false if the entity didn't know the command
    virtual bool act(vector<string> commands) = 0;

    string name;
    Map map;

private:
    int health;
};

struct Shogun : public Entity {
  Shogun() : Entity("Shogibear", 100) {}
};

struct Item
{
    virtual void apply(Entity* entity) = 0;
    virtual string identify() const = 0;
};

struct HealthItem : public Item
{
    HealthItem(int healPower) : healPower(healPower) {}

    void apply(Entity* entity) override
    {
        entity->heal(healPower);
    }

    string identify() const override
    {
        stringstream ss;
        ss << "Health Potion (" << healPower << ")";
        return ss.str();
    }

private:
    int healPower;
};
struct BlessedSword : public Item{BlessedSword(int Weapon) : Weapon(Weapon){}
void apply(Entity* entity) override{entity->weapon(Weapon);}string identify() const override{stringstream ss; ss << "Hit (" << Weapon << ")";}
private: int Weapon;};//will add this to entity on my next commit. <.<

struct TheFastcall : public Entity { TheFastcall("The Fastcall", 22); };

struct Player : public Entity
{
    Player(string name, int health) : Entity(name, health) {}

    virtual bool act(vector<string> commands) override
    {
        auto& cmd = commands[0];
        if(cmd == "n") { commands = vector<string>{"go","north"}; }
        if(cmd == "s") { commands = vector<string>{"go","south"}; }
        if(cmd == "e") { commands = vector<string>{"go","east"}; }
        if(cmd == "w") { commands = vector<string>{"go","west"}; }

        if (commands.size() >= 1 && commands[0] == "look")
        {
            look();
            return true;
        }
        else if (commands.size() >= 2 && (commands[0] == "examine" || commands[0] == "x"))
        {
        }
        else if (commands.size() >= 2 && commands[0] == "go")
        {
            if (travel(commands[1]) == true)
            {
                look();
            } else {
                cout << "Can't travel " << commands[1] << endl;
            }
            return true;
        }
        else if (commands.size() >= 1 && commands[0] == "items")
        {
            showItems();
            return true;
        }
        else if (commands.size() >= 2 && commands[0] == "use")
        {
            int index = stoi(commands[1]);
            useItem(index);
            return true;
        }

        return false;
    }

    bool travel(string direction)
    {
		if ((map.x <= 0 && direction == "west") || (map.x >= (map.max_width - 1) && direction == "east"))
			return false;
		if ((map.y <= 0 && direction == "south") || (map.y >= (map.max_width - 1) && direction == "north"))
			return false;
        if(direction=="north"&&map.map_location[map.x][map.y+1]==Map::UNKNOWN)return false;if(direction=="south"&&map.map_location[map.x][map.y-1]==Map::UNKNOWN)return false;if(direction=="east"&&map.map_location[map.x+1][map.y]==Map::UNKNOWN)return false
        ;if(direction=="west"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN)return false;if(direction=="north")map.y++;if(direction=="south")map.y--;if(direction=="east")map.x++;if(direction=="west")map.x--;
        return true;/*
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                if (direction == "north")
                {
					map.y++;
                    return true;
                }
                break;
            case Map::GRAVEYARD_GATES:
                if (direction == "south")
                {
					map.y--;
                    return true;
                }
                if (direction == "north")
                {
                    map.y++;
                    return true;
                }
                break;
        }

        cout << "Can't travel " << direction << endl;
        return false;*/
    }

    void look()
    {
        switch (map.map_location[map.x][map.y])
        {
            case Map::GRAVEYARD:
                cout << "A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place." << endl;
                break;
            case Map::GRAVEYARD_GATES:
                cout << "For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house." << endl;
                break;
            case Map::KHATHARRS_MOMS_HOUSE:
                cout << "The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east." << endl;
                break;
        }
    }

    void giveItem(shared_ptr<Item> item)
    {
        inventory.push_back(item);
    }

    void showItems()
    {
        if (inventory.size() == 0)
            cout << "You have no items." << endl;
        int i = 1;
        for (auto item : inventory)
        {
            cout << "  " << i++ << ". " << item->identify() << std::endl;
        }
    }

    void useItem(int index)
    {
        if (index > inventory.size())
        {
            cout << "Invalid index" << endl;
            return;
        }

        inventory[index-1]->apply(this);
        inventory.erase(inventory.begin() + index - 1);
    }

private:
    vector<shared_ptr<Item>> inventory;
};

class Adventure
{
public:
    void begin()
    {
        string command;
        cout << "Welcome, brave soul. Pray tell, what is thy name?" << endl;
        cout << "> ";
        getline(cin, command);

        Player player(command, 100);
        player.giveItem(make_shared<HealthItem>(20));

        cout << player.name << "! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later." << endl;
        player.look();

        while (player.getHealth() > 0)
        {
            cout << "> ";
            getline(cin, command);
            if (player.act(split(command)) == false)
                cout << "Unknown command" << endl;
        }

        cout << "You died. Game over." << endl;
    }
};

int main()
{
    Adventure adventure;
    adventure.begin();
    return 0;
}
<|endoftext|>