<commit_before>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg

// 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 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.

#define LUABIND_BUILDING

#include <luabind/lua_include.hpp>

#include <luabind/luabind.hpp>
#include <luabind/class_info.hpp>
#include <luabind/detail/class_registry.hpp>

/*
#include <iostream>
#define VERBOSE(X) std::cout << __FILE__ << ":" << __LINE__ << ": " << X << std::endl
*/
#define VERBOSE(X)

namespace luabind
{
	LUABIND_API class_info get_class_info(argument const& o)
	{
		lua_State* L = o.interpreter();
		detail::class_rep * crep = NULL;
		bool givenClassRep = false;

		o.push(L);
		if (detail::is_class_rep(L, -1)) {
			VERBOSE("OK, got a class rep");
			// OK, o is a class rep, now at the top of the stack
			givenClassRep = true;
			crep = static_cast<detail::class_rep *>(lua_touserdata(L, -1));
			lua_pop(L, 1);
		} else {

			VERBOSE("Not a class rep");
			detail::object_rep* obj = detail::get_instance(L, -1);

			if (!obj)
			{
				VERBOSE("Not a obj rep");
			    class_info result;
			    result.name = lua_typename(L, lua_type(L, -1));
			    lua_pop(L, 1);
			    result.methods = newtable(L);
			    result.attributes = newtable(L);
			    return result;
			} else {
		        lua_pop(L, 1);
				// OK, we were given an object - gotta get the crep.
				crep = obj->crep();
			}
		}
		crep->get_table(L);
        object table(from_stack(L, -1));
        lua_pop(L, 1);

        class_info result;
        result.name = crep->name();
        result.methods = newtable(L);
        result.attributes = newtable(L);

        std::size_t index = 1;

        for (iterator i(table), e; i != e; ++i)
        {
            if (type(*i) != LUA_TFUNCTION)
                continue;

            // We have to create a temporary `object` here, otherwise the proxy
            // returned by operator->() will mess up the stack. This is a known
            // problem that probably doesn't show up in real code very often.
            object member(*i);
            member.push(L);
            detail::stack_pop pop(L, 1);

            if (lua_tocfunction(L, -1) == &detail::property_tag)
            {
                result.attributes[index++] = i.key();
            }
            else
            {
                result.methods[i.key()] = *i;
            }
        }

        return result;
	}

    LUABIND_API object get_class_names(lua_State* L)
    {
        detail::class_registry* reg = detail::class_registry::get_registry(L);

        std::map<type_id, detail::class_rep*> const& classes = reg->get_classes();

        object result = newtable(L);
        std::size_t index = 1;

        for (std::map<type_id, detail::class_rep*>::const_iterator iter = classes.begin();
            iter != classes.end(); ++iter)
        {
            result[index++] = iter->second->name();
        }

        return result;
    }

	LUABIND_API void bind_class_info(lua_State* L)
	{
		module(L)
		[
			class_<class_info>("class_info_data")
				.def_readonly("name", &class_info::name)
				.def_readonly("methods", &class_info::methods)
				.def_readonly("attributes", &class_info::attributes),

            def("class_info", &get_class_info),
            def("class_names", &get_class_names)
		];
	}
}

<commit_msg>Make bind_class_info idempotent (can call repeatedly without breaking)<commit_after>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg

// 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 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.

#define LUABIND_BUILDING

#include <luabind/lua_include.hpp>

#include <luabind/luabind.hpp>
#include <luabind/class_info.hpp>
#include <luabind/detail/class_registry.hpp>

/*
#include <iostream>
#define VERBOSE(X) std::cout << __FILE__ << ":" << __LINE__ << ": " << X << std::endl
*/
#define VERBOSE(X)

namespace luabind
{
	LUABIND_API class_info get_class_info(argument const& o)
	{
		lua_State* L = o.interpreter();
		detail::class_rep * crep = NULL;
		bool givenClassRep = false;

		o.push(L);
		if (detail::is_class_rep(L, -1)) {
			VERBOSE("OK, got a class rep");
			// OK, o is a class rep, now at the top of the stack
			givenClassRep = true;
			crep = static_cast<detail::class_rep *>(lua_touserdata(L, -1));
			lua_pop(L, 1);
		} else {

			VERBOSE("Not a class rep");
			detail::object_rep* obj = detail::get_instance(L, -1);

			if (!obj)
			{
				VERBOSE("Not a obj rep");
			    class_info result;
			    result.name = lua_typename(L, lua_type(L, -1));
			    lua_pop(L, 1);
			    result.methods = newtable(L);
			    result.attributes = newtable(L);
			    return result;
			} else {
		        lua_pop(L, 1);
				// OK, we were given an object - gotta get the crep.
				crep = obj->crep();
			}
		}
		crep->get_table(L);
        object table(from_stack(L, -1));
        lua_pop(L, 1);

        class_info result;
        result.name = crep->name();
        result.methods = newtable(L);
        result.attributes = newtable(L);

        std::size_t index = 1;

        for (iterator i(table), e; i != e; ++i)
        {
            if (type(*i) != LUA_TFUNCTION)
                continue;

            // We have to create a temporary `object` here, otherwise the proxy
            // returned by operator->() will mess up the stack. This is a known
            // problem that probably doesn't show up in real code very often.
            object member(*i);
            member.push(L);
            detail::stack_pop pop(L, 1);

            if (lua_tocfunction(L, -1) == &detail::property_tag)
            {
                result.attributes[index++] = i.key();
            }
            else
            {
                result.methods[i.key()] = *i;
            }
        }

        return result;
	}

    LUABIND_API object get_class_names(lua_State* L)
    {
        detail::class_registry* reg = detail::class_registry::get_registry(L);

        std::map<type_id, detail::class_rep*> const& classes = reg->get_classes();

        object result = newtable(L);
        std::size_t index = 1;

        for (std::map<type_id, detail::class_rep*>::const_iterator iter = classes.begin();
            iter != classes.end(); ++iter)
        {
            result[index++] = iter->second->name();
        }

        return result;
    }

	LUABIND_API void bind_class_info(lua_State* L)
	{
		detail::class_registry* reg = detail::class_registry::get_registry(L);
		if (reg->find_class(typeid(class_info))) {
			// We've already been registered!
			return;
		}

		module(L)
		[
			class_<class_info>("class_info_data")
				.def_readonly("name", &class_info::name)
				.def_readonly("methods", &class_info::methods)
				.def_readonly("attributes", &class_info::attributes),

            def("class_info", &get_class_info),
            def("class_names", &get_class_names)
		];
	}
}

<|endoftext|>


<commit_before>#include <sys/socket.h>

#include "utils.h"
#include "cJSON.h"

#include "client_http.h"

//
// Xapian http client
//

HttpClient::HttpClient(ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)
	: BaseClient(loop, sock_, database_pool_, active_timeout_, idle_timeout_)
{
	parser.data = this;
	http_parser_init(&parser, HTTP_REQUEST);
	LOG_CONN(this, "Got connection (sock=%d), %d http client(s) connected.\n", sock, ++total_clients);
}

HttpClient::~HttpClient()
{
	total_clients--;
}

void HttpClient::on_read(const char *buf, ssize_t received)
{
	size_t parsed = http_parser_execute(&parser, &settings, buf, received);
	if (parsed == received) {
		if (parser.state == 1 || parser.state == 18) { // dead or message_complete
			try {
				//					LOG_HTTP_PROTO(this, "METHOD: %d\n", parser.method);
				//					LOG_HTTP_PROTO(this, "PATH: '%s'\n", repr(path).c_str());
				//					LOG_HTTP_PROTO(this, "BODY: '%s'\n", repr(body).c_str());

				std::string content;
				cJSON *json = cJSON_Parse(body.c_str());
				cJSON *query = json ? cJSON_GetObjectItem(json, "query") : NULL;
				cJSON *term = query ? cJSON_GetObjectItem(query, "term") : NULL;
				cJSON *text = term ? cJSON_GetObjectItem(term, "text") : NULL;

				cJSON *root = cJSON_CreateObject();
				cJSON *response = cJSON_CreateObject();
				cJSON_AddItemToObject(root, "response", response);
				if (text) {
					cJSON_AddStringToObject(response, "status", "OK");
					cJSON_AddStringToObject(response, "query", text->valuestring);
					cJSON_AddStringToObject(response, "title", "The title");
					cJSON_AddNumberToObject(response, "items", 7);
					const char *strings[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
					cJSON *results = cJSON_CreateArray();
					cJSON_AddItemToObject(response, "results", results);
					for (int i = 0; i < 7; i++) {
						cJSON *result = cJSON_CreateObject();
						cJSON_AddNumberToObject(result, "id", i);
						cJSON_AddStringToObject(result, "name", strings[i]);
						cJSON_AddItemToArray(results, result);
					}
				} else {
					LOG_HTTP_PROTO("Error before: [%s]\n", cJSON_GetErrorPtr());
					cJSON_AddStringToObject(response, "status", "ERROR");
					cJSON_AddStringToObject(response, "message", cJSON_GetErrorPtr());
				}
				cJSON_Delete(json);

				char *out = cJSON_Print(root);
				content = out;
				cJSON_Delete(root);
				free(out);

				char tmp[20];
				std::string http_response;
				http_response += "HTTP/";
				sprintf(tmp, "%d.%d", parser.http_major, parser.http_minor);
				http_response += tmp;
				http_response += " 200 OK\r\n";
				http_response += "Content-Type: application/json\r\n";
				http_response += "Content-Length: ";
				sprintf(tmp, "%ld", content.size());
				http_response += tmp;
				http_response += "\r\n";
				write(http_response + "\r\n" + content);
				if (parser.state == 1) close();
			} catch (...) {
				LOG_ERR(this, "ERROR!\n");
			}
		}
	} else {
		enum http_errno err = HTTP_PARSER_ERRNO(&parser);
		const char *desc = http_errno_description(err);
		const char *msg = err != HPE_OK ? desc : "incomplete request";
		LOG_HTTP_PROTO(this, msg);
		// Handle error. Just close the connection.
		destroy();
	}
}

//
// HTTP parser callbacks.
//

const http_parser_settings HttpClient::settings = {
	.on_message_begin = HttpClient::on_info,
	.on_url = HttpClient::on_data,
	.on_status = HttpClient::on_data,
	.on_header_field = HttpClient::on_data,
	.on_header_value = HttpClient::on_data,
	.on_headers_complete = HttpClient::on_info,
	.on_body = HttpClient::on_data,
	.on_message_complete = HttpClient::on_info
};

int HttpClient::on_info(http_parser* p) {
	HttpClient *self = static_cast<HttpClient *>(p->data);

	LOG_HTTP_PROTO_PARSER(self, "%3d. (INFO)\n", p->state);

	switch (p->state) {
		case 18:  // message_complete
			break;
		case 19:  // message_begin
			self->path.clear();
			self->body.clear();
			break;
	}

	return 0;
}

int HttpClient::on_data(http_parser* p, const char *at, size_t length) {
	HttpClient *self = static_cast<HttpClient *>(p->data);

	LOG_HTTP_PROTO_PARSER(self, "%3d. %s\n", p->state, repr(at, length).c_str());

	switch (p->state) {
		case 32: // path
			self->path = std::string(at, length);
			break;
		case 62: // data
			self->body = std::string(at, length);
			break;
	}

	return 0;
}
<commit_msg>Unformatted json returned<commit_after>#include <sys/socket.h>

#include "utils.h"
#include "cJSON.h"

#include "client_http.h"

//
// Xapian http client
//

HttpClient::HttpClient(ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)
	: BaseClient(loop, sock_, database_pool_, active_timeout_, idle_timeout_)
{
	parser.data = this;
	http_parser_init(&parser, HTTP_REQUEST);
	LOG_CONN(this, "Got connection (sock=%d), %d http client(s) connected.\n", sock, ++total_clients);
}

HttpClient::~HttpClient()
{
	total_clients--;
}

void HttpClient::on_read(const char *buf, ssize_t received)
{
	size_t parsed = http_parser_execute(&parser, &settings, buf, received);
	if (parsed == received) {
		if (parser.state == 1 || parser.state == 18) { // dead or message_complete
			try {
				//					LOG_HTTP_PROTO(this, "METHOD: %d\n", parser.method);
				//					LOG_HTTP_PROTO(this, "PATH: '%s'\n", repr(path).c_str());
				//					LOG_HTTP_PROTO(this, "BODY: '%s'\n", repr(body).c_str());

				std::string content;
				cJSON *json = cJSON_Parse(body.c_str());
				cJSON *query = json ? cJSON_GetObjectItem(json, "query") : NULL;
				cJSON *term = query ? cJSON_GetObjectItem(query, "term") : NULL;
				cJSON *text = term ? cJSON_GetObjectItem(term, "text") : NULL;

				cJSON *root = cJSON_CreateObject();
				cJSON *response = cJSON_CreateObject();
				cJSON_AddItemToObject(root, "response", response);
				if (text) {
					cJSON_AddStringToObject(response, "status", "OK");
					cJSON_AddStringToObject(response, "query", text->valuestring);
					cJSON_AddStringToObject(response, "title", "The title");
					cJSON_AddNumberToObject(response, "items", 7);
					const char *strings[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
					cJSON *results = cJSON_CreateArray();
					cJSON_AddItemToObject(response, "results", results);
					for (int i = 0; i < 7; i++) {
						cJSON *result = cJSON_CreateObject();
						cJSON_AddNumberToObject(result, "id", i);
						cJSON_AddStringToObject(result, "name", strings[i]);
						cJSON_AddItemToArray(results, result);
					}
				} else {
					LOG_HTTP_PROTO("Error before: [%s]\n", cJSON_GetErrorPtr());
					cJSON_AddStringToObject(response, "status", "ERROR");
					cJSON_AddStringToObject(response, "message", cJSON_GetErrorPtr());
				}
				cJSON_Delete(json);

				bool pretty = false;
				char *out;
				if (pretty) {
					out = cJSON_Print(root);
				} else {
					out = cJSON_PrintUnformatted(root);
				}
				content = out;
				cJSON_Delete(root);
				free(out);

				char tmp[20];
				std::string http_response;
				http_response += "HTTP/";
				sprintf(tmp, "%d.%d", parser.http_major, parser.http_minor);
				http_response += tmp;
				http_response += " 200 OK\r\n";
				http_response += "Content-Type: application/json\r\n";
				http_response += "Content-Length: ";
				sprintf(tmp, "%ld", content.size());
				http_response += tmp;
				http_response += "\r\n";
				write(http_response + "\r\n" + content);
				if (parser.state == 1) close();
			} catch (...) {
				LOG_ERR(this, "ERROR!\n");
			}
		}
	} else {
		enum http_errno err = HTTP_PARSER_ERRNO(&parser);
		const char *desc = http_errno_description(err);
		const char *msg = err != HPE_OK ? desc : "incomplete request";
		LOG_HTTP_PROTO(this, msg);
		// Handle error. Just close the connection.
		destroy();
	}
}

//
// HTTP parser callbacks.
//

const http_parser_settings HttpClient::settings = {
	.on_message_begin = HttpClient::on_info,
	.on_url = HttpClient::on_data,
	.on_status = HttpClient::on_data,
	.on_header_field = HttpClient::on_data,
	.on_header_value = HttpClient::on_data,
	.on_headers_complete = HttpClient::on_info,
	.on_body = HttpClient::on_data,
	.on_message_complete = HttpClient::on_info
};

int HttpClient::on_info(http_parser* p) {
	HttpClient *self = static_cast<HttpClient *>(p->data);

	LOG_HTTP_PROTO_PARSER(self, "%3d. (INFO)\n", p->state);

	switch (p->state) {
		case 18:  // message_complete
			break;
		case 19:  // message_begin
			self->path.clear();
			self->body.clear();
			break;
	}

	return 0;
}

int HttpClient::on_data(http_parser* p, const char *at, size_t length) {
	HttpClient *self = static_cast<HttpClient *>(p->data);

	LOG_HTTP_PROTO_PARSER(self, "%3d. %s\n", p->state, repr(at, length).c_str());

	switch (p->state) {
		case 32: // path
			self->path = std::string(at, length);
			break;
		case 62: // data
			self->body = std::string(at, length);
			break;
	}

	return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright © 2010 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.
 */

extern "C" {
#include "main/macros.h"
#include "brw_context.h"
#include "brw_vs.h"
}
#include "brw_fs.h"
#include "glsl/ir_optimization.h"
#include "glsl/ir_print_visitor.h"

struct gl_shader *
brw_new_shader(struct gl_context *ctx, GLuint name, GLuint type)
{
   struct brw_shader *shader;

   shader = rzalloc(NULL, struct brw_shader);
   if (shader) {
      shader->base.Type = type;
      shader->base.Name = name;
      _mesa_init_shader(ctx, &shader->base);
   }

   return &shader->base;
}

struct gl_shader_program *
brw_new_shader_program(struct gl_context *ctx, GLuint name)
{
   struct gl_shader_program *prog = rzalloc(NULL, struct gl_shader_program);
   if (prog) {
      prog->Name = name;
      _mesa_init_shader_program(ctx, prog);
   }
   return prog;
}

/**
 * Performs a compile of the shader stages even when we don't know
 * what non-orthogonal state will be set, in the hope that it reflects
 * the eventual NOS used, and thus allows us to produce link failures.
 */
static bool
brw_shader_precompile(struct gl_context *ctx, struct gl_shader_program *prog)
{
   struct brw_context *brw = brw_context(ctx);

   if (brw->precompile && !brw_fs_precompile(ctx, prog))
      return false;

   if (brw->precompile && !brw_vs_precompile(ctx, prog))
      return false;

   return true;
}

static void
brw_lower_packing_builtins(struct brw_context *brw,
                           gl_shader_type shader_type,
                           exec_list *ir)
{
   int ops = LOWER_PACK_SNORM_2x16
           | LOWER_UNPACK_SNORM_2x16
           | LOWER_PACK_UNORM_2x16
           | LOWER_UNPACK_UNORM_2x16;

   if (brw->intel.gen >= 7) {
      /* Gen7 introduced the f32to16 and f16to32 instructions, which can be
       * used to execute packHalf2x16 and unpackHalf2x16. For AOS code, no
       * lowering is needed. For SOA code, the Half2x16 ops must be
       * scalarized.
       */
      if (shader_type == MESA_SHADER_FRAGMENT) {
         ops |= LOWER_PACK_HALF_2x16_TO_SPLIT
             |  LOWER_UNPACK_HALF_2x16_TO_SPLIT;
      }
   } else {
      ops |= LOWER_PACK_HALF_2x16
          |  LOWER_UNPACK_HALF_2x16;
   }

   lower_packing_builtins(ir, ops);
}

GLboolean
brw_link_shader(struct gl_context *ctx, struct gl_shader_program *shProg)
{
   struct brw_context *brw = brw_context(ctx);
   struct intel_context *intel = &brw->intel;
   unsigned int stage;

   for (stage = 0; stage < ARRAY_SIZE(shProg->_LinkedShaders); stage++) {
      struct brw_shader *shader =
	 (struct brw_shader *)shProg->_LinkedShaders[stage];
      static const GLenum targets[] = {
	 GL_VERTEX_PROGRAM_ARB,
	 GL_FRAGMENT_PROGRAM_ARB,
	 GL_GEOMETRY_PROGRAM_NV
      };

      if (!shader)
	 continue;

      struct gl_program *prog =
	 ctx->Driver.NewProgram(ctx, targets[stage], shader->base.Name);
      if (!prog)
	return false;
      prog->Parameters = _mesa_new_parameter_list();

      if (stage == 0) {
	 struct gl_vertex_program *vp = (struct gl_vertex_program *) prog;
	 vp->UsesClipDistance = shProg->Vert.UsesClipDistance;
      }

      void *mem_ctx = ralloc_context(NULL);
      bool progress;

      if (shader->ir)
	 ralloc_free(shader->ir);
      shader->ir = new(shader) exec_list;
      clone_ir_list(mem_ctx, shader->ir, shader->base.ir);

      /* lower_packing_builtins() inserts arithmetic instructions, so it
       * must precede lower_instructions().
       */
      brw_lower_packing_builtins(brw, (gl_shader_type) stage, shader->ir);
      do_mat_op_to_vec(shader->ir);
      lower_instructions(shader->ir,
			 MOD_TO_FRACT |
			 DIV_TO_MUL_RCP |
			 SUB_TO_ADD_NEG |
			 EXP_TO_EXP2 |
			 LOG_TO_LOG2);

      /* Pre-gen6 HW can only nest if-statements 16 deep.  Beyond this,
       * if-statements need to be flattened.
       */
      if (intel->gen < 6)
	 lower_if_to_cond_assign(shader->ir, 16);

      do_lower_texture_projection(shader->ir);
      if (intel->gen < 8 && !intel->is_haswell)
         brw_lower_texture_gradients(shader->ir);
      do_vec_index_to_cond_assign(shader->ir);
      brw_do_cubemap_normalize(shader->ir);
      lower_noise(shader->ir);
      lower_quadop_vector(shader->ir, false);

      bool input = true;
      bool output = stage == MESA_SHADER_FRAGMENT;
      bool temp = stage == MESA_SHADER_FRAGMENT;
      bool uniform = false;

      bool lowered_variable_indexing =
         lower_variable_index_to_cond_assign(shader->ir,
                                             input, output, temp, uniform);

      if (unlikely((INTEL_DEBUG & DEBUG_PERF) && lowered_variable_indexing)) {
         perf_debug("Unsupported form of variable indexing in FS; falling "
                    "back to very inefficient code generation\n");
      }

      /* FINISHME: Do this before the variable index lowering. */
      lower_ubo_reference(&shader->base, shader->ir);

      do {
	 progress = false;

	 if (stage == MESA_SHADER_FRAGMENT) {
	    brw_do_channel_expressions(shader->ir);
	    brw_do_vector_splitting(shader->ir);
	 }

	 progress = do_lower_jumps(shader->ir, true, true,
				   true, /* main return */
				   false, /* continue */
				   false /* loops */
				   ) || progress;

	 progress = do_common_optimization(shader->ir, true, true, 32)
	   || progress;
      } while (progress);

      /* Make a pass over the IR to add state references for any built-in
       * uniforms that are used.  This has to be done now (during linking).
       * Code generation doesn't happen until the first time this shader is
       * used for rendering.  Waiting until then to generate the parameters is
       * too late.  At that point, the values for the built-in uniforms won't
       * get sent to the shader.
       */
      foreach_list(node, shader->ir) {
	 ir_variable *var = ((ir_instruction *) node)->as_variable();

	 if ((var == NULL) || (var->mode != ir_var_uniform)
	     || (strncmp(var->name, "gl_", 3) != 0))
	    continue;

	 const ir_state_slot *const slots = var->state_slots;
	 assert(var->state_slots != NULL);

	 for (unsigned int i = 0; i < var->num_state_slots; i++) {
	    _mesa_add_state_reference(prog->Parameters,
				      (gl_state_index *) slots[i].tokens);
	 }
      }

      validate_ir_tree(shader->ir);

      reparent_ir(shader->ir, shader->ir);
      ralloc_free(mem_ctx);

      do_set_program_inouts(shader->ir, prog,
			    shader->base.Type == GL_FRAGMENT_SHADER);

      prog->SamplersUsed = shader->base.active_samplers;
      _mesa_update_shader_textures_used(shProg, prog);

      _mesa_reference_program(ctx, &shader->base.Program, prog);

      brw_add_texrect_params(prog);

      /* This has to be done last.  Any operation that can cause
       * prog->ParameterValues to get reallocated (e.g., anything that adds a
       * program constant) has to happen before creating this linkage.
       */
      _mesa_associate_uniform_storage(ctx, shProg, prog->Parameters);

      _mesa_reference_program(ctx, &prog, NULL);

      if (ctx->Shader.Flags & GLSL_DUMP) {
         static const char *target_strings[]
            = { "vertex", "fragment", "geometry" };
         printf("\n");
         printf("GLSL IR for linked %s program %d:\n", target_strings[stage],
                shProg->Name);
         _mesa_print_ir(shader->base.ir, NULL);
      }
   }

   if (!brw_shader_precompile(ctx, shProg))
      return false;

   return true;
}

int
brw_type_for_base_type(const struct glsl_type *type)
{
   switch (type->base_type) {
   case GLSL_TYPE_FLOAT:
      return BRW_REGISTER_TYPE_F;
   case GLSL_TYPE_INT:
   case GLSL_TYPE_BOOL:
      return BRW_REGISTER_TYPE_D;
   case GLSL_TYPE_UINT:
      return BRW_REGISTER_TYPE_UD;
   case GLSL_TYPE_ARRAY:
      return brw_type_for_base_type(type->fields.array);
   case GLSL_TYPE_STRUCT:
   case GLSL_TYPE_SAMPLER:
      /* These should be overridden with the type of the member when
       * dereferenced into.  BRW_REGISTER_TYPE_UD seems like a likely
       * way to trip up if we don't.
       */
      return BRW_REGISTER_TYPE_UD;
   case GLSL_TYPE_VOID:
   case GLSL_TYPE_ERROR:
   case GLSL_TYPE_INTERFACE:
      assert(!"not reached");
      break;
   }

   return BRW_REGISTER_TYPE_F;
}

uint32_t
brw_conditional_for_comparison(unsigned int op)
{
   switch (op) {
   case ir_binop_less:
      return BRW_CONDITIONAL_L;
   case ir_binop_greater:
      return BRW_CONDITIONAL_G;
   case ir_binop_lequal:
      return BRW_CONDITIONAL_LE;
   case ir_binop_gequal:
      return BRW_CONDITIONAL_GE;
   case ir_binop_equal:
   case ir_binop_all_equal: /* same as equal for scalars */
      return BRW_CONDITIONAL_Z;
   case ir_binop_nequal:
   case ir_binop_any_nequal: /* same as nequal for scalars */
      return BRW_CONDITIONAL_NZ;
   default:
      assert(!"not reached: bad operation for comparison");
      return BRW_CONDITIONAL_NZ;
   }
}

uint32_t
brw_math_function(enum opcode op)
{
   switch (op) {
   case SHADER_OPCODE_RCP:
      return BRW_MATH_FUNCTION_INV;
   case SHADER_OPCODE_RSQ:
      return BRW_MATH_FUNCTION_RSQ;
   case SHADER_OPCODE_SQRT:
      return BRW_MATH_FUNCTION_SQRT;
   case SHADER_OPCODE_EXP2:
      return BRW_MATH_FUNCTION_EXP;
   case SHADER_OPCODE_LOG2:
      return BRW_MATH_FUNCTION_LOG;
   case SHADER_OPCODE_POW:
      return BRW_MATH_FUNCTION_POW;
   case SHADER_OPCODE_SIN:
      return BRW_MATH_FUNCTION_SIN;
   case SHADER_OPCODE_COS:
      return BRW_MATH_FUNCTION_COS;
   case SHADER_OPCODE_INT_QUOTIENT:
      return BRW_MATH_FUNCTION_INT_DIV_QUOTIENT;
   case SHADER_OPCODE_INT_REMAINDER:
      return BRW_MATH_FUNCTION_INT_DIV_REMAINDER;
   default:
      assert(!"not reached: unknown math function");
      return 0;
   }
}

uint32_t
brw_texture_offset(ir_constant *offset)
{
   assert(offset != NULL);

   signed char offsets[3];
   for (unsigned i = 0; i < offset->type->vector_elements; i++)
      offsets[i] = (signed char) offset->value.i[i];

   /* Combine all three offsets into a single unsigned dword:
    *
    *    bits 11:8 - U Offset (X component)
    *    bits  7:4 - V Offset (Y component)
    *    bits  3:0 - R Offset (Z component)
    */
   unsigned offset_bits = 0;
   for (unsigned i = 0; i < offset->type->vector_elements; i++) {
      const unsigned shift = 4 * (2 - i);
      offset_bits |= (offsets[i] << shift) & (0xF << shift);
   }
   return offset_bits;
}
<commit_msg>i965: Lower the 4x8 pack/unpack operations<commit_after>/*
 * Copyright © 2010 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.
 */

extern "C" {
#include "main/macros.h"
#include "brw_context.h"
#include "brw_vs.h"
}
#include "brw_fs.h"
#include "glsl/ir_optimization.h"
#include "glsl/ir_print_visitor.h"

struct gl_shader *
brw_new_shader(struct gl_context *ctx, GLuint name, GLuint type)
{
   struct brw_shader *shader;

   shader = rzalloc(NULL, struct brw_shader);
   if (shader) {
      shader->base.Type = type;
      shader->base.Name = name;
      _mesa_init_shader(ctx, &shader->base);
   }

   return &shader->base;
}

struct gl_shader_program *
brw_new_shader_program(struct gl_context *ctx, GLuint name)
{
   struct gl_shader_program *prog = rzalloc(NULL, struct gl_shader_program);
   if (prog) {
      prog->Name = name;
      _mesa_init_shader_program(ctx, prog);
   }
   return prog;
}

/**
 * Performs a compile of the shader stages even when we don't know
 * what non-orthogonal state will be set, in the hope that it reflects
 * the eventual NOS used, and thus allows us to produce link failures.
 */
static bool
brw_shader_precompile(struct gl_context *ctx, struct gl_shader_program *prog)
{
   struct brw_context *brw = brw_context(ctx);

   if (brw->precompile && !brw_fs_precompile(ctx, prog))
      return false;

   if (brw->precompile && !brw_vs_precompile(ctx, prog))
      return false;

   return true;
}

static void
brw_lower_packing_builtins(struct brw_context *brw,
                           gl_shader_type shader_type,
                           exec_list *ir)
{
   int ops = LOWER_PACK_SNORM_2x16
           | LOWER_UNPACK_SNORM_2x16
           | LOWER_PACK_UNORM_2x16
           | LOWER_UNPACK_UNORM_2x16
           | LOWER_PACK_SNORM_4x8
           | LOWER_UNPACK_SNORM_4x8
           | LOWER_PACK_UNORM_4x8
           | LOWER_UNPACK_UNORM_4x8;

   if (brw->intel.gen >= 7) {
      /* Gen7 introduced the f32to16 and f16to32 instructions, which can be
       * used to execute packHalf2x16 and unpackHalf2x16. For AOS code, no
       * lowering is needed. For SOA code, the Half2x16 ops must be
       * scalarized.
       */
      if (shader_type == MESA_SHADER_FRAGMENT) {
         ops |= LOWER_PACK_HALF_2x16_TO_SPLIT
             |  LOWER_UNPACK_HALF_2x16_TO_SPLIT;
      }
   } else {
      ops |= LOWER_PACK_HALF_2x16
          |  LOWER_UNPACK_HALF_2x16;
   }

   lower_packing_builtins(ir, ops);
}

GLboolean
brw_link_shader(struct gl_context *ctx, struct gl_shader_program *shProg)
{
   struct brw_context *brw = brw_context(ctx);
   struct intel_context *intel = &brw->intel;
   unsigned int stage;

   for (stage = 0; stage < ARRAY_SIZE(shProg->_LinkedShaders); stage++) {
      struct brw_shader *shader =
	 (struct brw_shader *)shProg->_LinkedShaders[stage];
      static const GLenum targets[] = {
	 GL_VERTEX_PROGRAM_ARB,
	 GL_FRAGMENT_PROGRAM_ARB,
	 GL_GEOMETRY_PROGRAM_NV
      };

      if (!shader)
	 continue;

      struct gl_program *prog =
	 ctx->Driver.NewProgram(ctx, targets[stage], shader->base.Name);
      if (!prog)
	return false;
      prog->Parameters = _mesa_new_parameter_list();

      if (stage == 0) {
	 struct gl_vertex_program *vp = (struct gl_vertex_program *) prog;
	 vp->UsesClipDistance = shProg->Vert.UsesClipDistance;
      }

      void *mem_ctx = ralloc_context(NULL);
      bool progress;

      if (shader->ir)
	 ralloc_free(shader->ir);
      shader->ir = new(shader) exec_list;
      clone_ir_list(mem_ctx, shader->ir, shader->base.ir);

      /* lower_packing_builtins() inserts arithmetic instructions, so it
       * must precede lower_instructions().
       */
      brw_lower_packing_builtins(brw, (gl_shader_type) stage, shader->ir);
      do_mat_op_to_vec(shader->ir);
      lower_instructions(shader->ir,
			 MOD_TO_FRACT |
			 DIV_TO_MUL_RCP |
			 SUB_TO_ADD_NEG |
			 EXP_TO_EXP2 |
			 LOG_TO_LOG2);

      /* Pre-gen6 HW can only nest if-statements 16 deep.  Beyond this,
       * if-statements need to be flattened.
       */
      if (intel->gen < 6)
	 lower_if_to_cond_assign(shader->ir, 16);

      do_lower_texture_projection(shader->ir);
      if (intel->gen < 8 && !intel->is_haswell)
         brw_lower_texture_gradients(shader->ir);
      do_vec_index_to_cond_assign(shader->ir);
      brw_do_cubemap_normalize(shader->ir);
      lower_noise(shader->ir);
      lower_quadop_vector(shader->ir, false);

      bool input = true;
      bool output = stage == MESA_SHADER_FRAGMENT;
      bool temp = stage == MESA_SHADER_FRAGMENT;
      bool uniform = false;

      bool lowered_variable_indexing =
         lower_variable_index_to_cond_assign(shader->ir,
                                             input, output, temp, uniform);

      if (unlikely((INTEL_DEBUG & DEBUG_PERF) && lowered_variable_indexing)) {
         perf_debug("Unsupported form of variable indexing in FS; falling "
                    "back to very inefficient code generation\n");
      }

      /* FINISHME: Do this before the variable index lowering. */
      lower_ubo_reference(&shader->base, shader->ir);

      do {
	 progress = false;

	 if (stage == MESA_SHADER_FRAGMENT) {
	    brw_do_channel_expressions(shader->ir);
	    brw_do_vector_splitting(shader->ir);
	 }

	 progress = do_lower_jumps(shader->ir, true, true,
				   true, /* main return */
				   false, /* continue */
				   false /* loops */
				   ) || progress;

	 progress = do_common_optimization(shader->ir, true, true, 32)
	   || progress;
      } while (progress);

      /* Make a pass over the IR to add state references for any built-in
       * uniforms that are used.  This has to be done now (during linking).
       * Code generation doesn't happen until the first time this shader is
       * used for rendering.  Waiting until then to generate the parameters is
       * too late.  At that point, the values for the built-in uniforms won't
       * get sent to the shader.
       */
      foreach_list(node, shader->ir) {
	 ir_variable *var = ((ir_instruction *) node)->as_variable();

	 if ((var == NULL) || (var->mode != ir_var_uniform)
	     || (strncmp(var->name, "gl_", 3) != 0))
	    continue;

	 const ir_state_slot *const slots = var->state_slots;
	 assert(var->state_slots != NULL);

	 for (unsigned int i = 0; i < var->num_state_slots; i++) {
	    _mesa_add_state_reference(prog->Parameters,
				      (gl_state_index *) slots[i].tokens);
	 }
      }

      validate_ir_tree(shader->ir);

      reparent_ir(shader->ir, shader->ir);
      ralloc_free(mem_ctx);

      do_set_program_inouts(shader->ir, prog,
			    shader->base.Type == GL_FRAGMENT_SHADER);

      prog->SamplersUsed = shader->base.active_samplers;
      _mesa_update_shader_textures_used(shProg, prog);

      _mesa_reference_program(ctx, &shader->base.Program, prog);

      brw_add_texrect_params(prog);

      /* This has to be done last.  Any operation that can cause
       * prog->ParameterValues to get reallocated (e.g., anything that adds a
       * program constant) has to happen before creating this linkage.
       */
      _mesa_associate_uniform_storage(ctx, shProg, prog->Parameters);

      _mesa_reference_program(ctx, &prog, NULL);

      if (ctx->Shader.Flags & GLSL_DUMP) {
         static const char *target_strings[]
            = { "vertex", "fragment", "geometry" };
         printf("\n");
         printf("GLSL IR for linked %s program %d:\n", target_strings[stage],
                shProg->Name);
         _mesa_print_ir(shader->base.ir, NULL);
      }
   }

   if (!brw_shader_precompile(ctx, shProg))
      return false;

   return true;
}

int
brw_type_for_base_type(const struct glsl_type *type)
{
   switch (type->base_type) {
   case GLSL_TYPE_FLOAT:
      return BRW_REGISTER_TYPE_F;
   case GLSL_TYPE_INT:
   case GLSL_TYPE_BOOL:
      return BRW_REGISTER_TYPE_D;
   case GLSL_TYPE_UINT:
      return BRW_REGISTER_TYPE_UD;
   case GLSL_TYPE_ARRAY:
      return brw_type_for_base_type(type->fields.array);
   case GLSL_TYPE_STRUCT:
   case GLSL_TYPE_SAMPLER:
      /* These should be overridden with the type of the member when
       * dereferenced into.  BRW_REGISTER_TYPE_UD seems like a likely
       * way to trip up if we don't.
       */
      return BRW_REGISTER_TYPE_UD;
   case GLSL_TYPE_VOID:
   case GLSL_TYPE_ERROR:
   case GLSL_TYPE_INTERFACE:
      assert(!"not reached");
      break;
   }

   return BRW_REGISTER_TYPE_F;
}

uint32_t
brw_conditional_for_comparison(unsigned int op)
{
   switch (op) {
   case ir_binop_less:
      return BRW_CONDITIONAL_L;
   case ir_binop_greater:
      return BRW_CONDITIONAL_G;
   case ir_binop_lequal:
      return BRW_CONDITIONAL_LE;
   case ir_binop_gequal:
      return BRW_CONDITIONAL_GE;
   case ir_binop_equal:
   case ir_binop_all_equal: /* same as equal for scalars */
      return BRW_CONDITIONAL_Z;
   case ir_binop_nequal:
   case ir_binop_any_nequal: /* same as nequal for scalars */
      return BRW_CONDITIONAL_NZ;
   default:
      assert(!"not reached: bad operation for comparison");
      return BRW_CONDITIONAL_NZ;
   }
}

uint32_t
brw_math_function(enum opcode op)
{
   switch (op) {
   case SHADER_OPCODE_RCP:
      return BRW_MATH_FUNCTION_INV;
   case SHADER_OPCODE_RSQ:
      return BRW_MATH_FUNCTION_RSQ;
   case SHADER_OPCODE_SQRT:
      return BRW_MATH_FUNCTION_SQRT;
   case SHADER_OPCODE_EXP2:
      return BRW_MATH_FUNCTION_EXP;
   case SHADER_OPCODE_LOG2:
      return BRW_MATH_FUNCTION_LOG;
   case SHADER_OPCODE_POW:
      return BRW_MATH_FUNCTION_POW;
   case SHADER_OPCODE_SIN:
      return BRW_MATH_FUNCTION_SIN;
   case SHADER_OPCODE_COS:
      return BRW_MATH_FUNCTION_COS;
   case SHADER_OPCODE_INT_QUOTIENT:
      return BRW_MATH_FUNCTION_INT_DIV_QUOTIENT;
   case SHADER_OPCODE_INT_REMAINDER:
      return BRW_MATH_FUNCTION_INT_DIV_REMAINDER;
   default:
      assert(!"not reached: unknown math function");
      return 0;
   }
}

uint32_t
brw_texture_offset(ir_constant *offset)
{
   assert(offset != NULL);

   signed char offsets[3];
   for (unsigned i = 0; i < offset->type->vector_elements; i++)
      offsets[i] = (signed char) offset->value.i[i];

   /* Combine all three offsets into a single unsigned dword:
    *
    *    bits 11:8 - U Offset (X component)
    *    bits  7:4 - V Offset (Y component)
    *    bits  3:0 - R Offset (Z component)
    */
   unsigned offset_bits = 0;
   for (unsigned i = 0; i < offset->type->vector_elements; i++) {
      const unsigned shift = 4 * (2 - i);
      offset_bits |= (offsets[i] << shift) & (0xF << shift);
   }
   return offset_bits;
}
<|endoftext|>


<commit_before><commit_msg>minor follow-up changes<commit_after><|endoftext|>


<commit_before>/*
 *   CrissCross
 *   A multi-purpose cross-platform library.
 *
 *   A product of Uplink Laboratories.
 *
 *   (c) 2006-2008 Steven Noonan.
 *   Licensed under the New BSD License.
 *
 */

#include <crisscross/universal_include.h>
#include <crisscross/debug.h>
#include <crisscross/console.h>

namespace CrissCross
{
	namespace IO
	{
		Console::Console ( bool _clearOnInit ):
		CoreIOWriter ( stdout, false, CC_LN_LF ),
		CoreIOReader ( stdin, false, CC_LN_LF )
		{
		#ifdef TARGET_OS_WINDOWS
			m_consoleAllocated = false;
			if ( AllocConsole () == TRUE )
			{
				m_consoleAllocated = true;
				int hCrt = _open_osfhandle ( ( intptr_t ) GetStdHandle ( STD_OUTPUT_HANDLE ), _O_TEXT );
				FILE *hf = _fdopen ( hCrt, "w" );

				*stdout = *hf;
				int i = setvbuf ( stdout, NULL, _IONBF, 0 );

				hCrt =
					_open_osfhandle ( ( intptr_t ) GetStdHandle ( STD_ERROR_HANDLE ),
									  _O_TEXT );
				hf = _fdopen ( hCrt, "w" );
				*stderr = *hf;
				i = setvbuf ( stdout, NULL, _IONBF, 0 );
			}

			if ( _clearOnInit ) Clear();

			SetTitle ( CC_LIB_NAME " " CC_LIB_VERSION " (Codename " CC_LIB_CODENAME ")" );
        #elif defined ( TARGET_OS_NDSFIRMWARE )
            irqInit();
            irqEnable(IRQ_VBLANK);
            videoSetMode(MODE_0_2D);
            videoSetModeSub(MODE_0_2D | DISPLAY_BG0_ACTIVE);
            vramSetBankC(VRAM_C_SUB_BG);
	        SUB_BG0_CR = BG_MAP_BASE(31);
	        BG_PALETTE_SUB[255] = RGB15(31,31,31);
	        consoleInitDefault((u16*)SCREEN_BASE_BLOCK_SUB(31), (u16*)CHAR_BASE_BLOCK_SUB(0), 16);
		#endif
		#ifdef ENABLE_CREDITS
        #if defined ( TARGET_OS_NDSFIRMWARE )
			g_stdout->SetColour ( g_stdout->FG_GREEN | g_stdout->FG_INTENSITY );
			g_stdout->WriteLine ( "Powered by " CC_LIB_NAME " v" CC_LIB_VERSION );
			g_stdout->SetColour ( 0 );
			g_stdout->WriteLine ( CC_LIB_NDS_COPYRIGHT );
			g_stdout->WriteLine ();
        #else
			g_stdout->SetColour ( g_stdout->FG_GREEN | g_stdout->FG_INTENSITY );
			g_stdout->WriteLine ( "Powered by " CC_LIB_NAME " " CC_LIB_VERSION " (Codename " CC_LIB_CODENAME ")\n    " CC_LIB_URL );
			g_stdout->SetColour ( 0 );
			g_stdout->WriteLine ( CC_LIB_COPYRIGHT );
			g_stdout->WriteLine ();
        #endif
		#endif
		}

		Console::Console ( FILE * _outputBuffer, FILE *_inputBuffer ):
		CoreIOWriter ( _outputBuffer, false, CC_LN_LF ),
		CoreIOReader ( _inputBuffer, false, CC_LN_LF )
		{
		}

		Console::~Console ()
		{
			SetColour ( 0 );
		#ifdef TARGET_OS_WINDOWS
			if ( m_consoleAllocated ) FreeConsole ();
		#endif
		}

		void
		Console::SetColour ()
		{
			SetColour ( 0 );
		}

		void
		Console::SetColour ( int _flags )
		{
			CoreAssert ( this != NULL );

		#if !defined ( ANSI_COLOUR ) && defined ( TARGET_OS_WINDOWS )
			HANDLE hConsole = GetStdHandle ( STD_OUTPUT_HANDLE );

			if ( _flags == 0 )
				SetConsoleTextAttribute ( hConsole, FG_GRAY );
			else
				SetConsoleTextAttribute ( hConsole, _flags );
		#elif defined ( ANSI_COLOUR )
			// Reset colours to defaults.
			Write ( "\033[39m" );

			if ( _flags == 0 )
				return;

			char codes[16];

			sprintf ( codes, "\033[" );

			if ( _flags & FG_INTENSITY )
				strcat ( codes, "1;" );
			if ( _flags & FG_RED )
				strcat ( codes, "31;" );
			if ( _flags & FG_GREEN )
				strcat ( codes, "32;" );
			if ( _flags & FG_BROWN )
				strcat ( codes, "33;" );
			if ( _flags & FG_BLUE )
				strcat ( codes, "34;" );
			if ( _flags & FG_MAGENTA )
				strcat ( codes, "35;" );
			if ( _flags & FG_CYAN )
				strcat ( codes, "36;" );
			if ( _flags & FG_GRAY )
				strcat ( codes, "37;" );
			if ( _flags & FG_WHITE )
				strcat ( codes, "39;" );

			/*
			   TODO: Determine if there is an ANSI code for background color intensity.
			   if ( _flags & BG_INTENSITY )
			   strcat ( codes, "???????" );
			 */
			if ( _flags & BG_RED )
				strcat ( codes, "41;" );
			if ( _flags & BG_GREEN )
				strcat ( codes, "42;" );
			if ( _flags & BG_BROWN )
				strcat ( codes, "43;" );
			if ( _flags & BG_BLUE )
				strcat ( codes, "44;" );
			if ( _flags & BG_MAGENTA )
				strcat ( codes, "45;" );
			if ( _flags & BG_CYAN )
				strcat ( codes, "46;" );
			if ( _flags & BG_WHITE )
				strcat ( codes, "47;" );

			codes[strlen ( codes ) - 1] = 'm';

			Write ( "%s", codes );
		#endif
		}

		void
		Console::SetTitle ( const char *_title )
		{
		#ifdef TARGET_OS_WINDOWS
			SetConsoleTitleA ( _title );
		#endif
		}

		void
		Console::SetTitle ( std::string &_title )
		{
			SetTitle ( _title.c_str () );
		}

		void
		Console::Clear ()
		{
			CoreAssert ( this != NULL );

		#if defined ( TARGET_OS_WINDOWS )
			COORD coordScreen = { 0, 0 };
			DWORD cCharsWritten;
			CONSOLE_SCREEN_BUFFER_INFO csbi;
			DWORD dwConSize;
			HANDLE hConsole = GetStdHandle ( STD_OUTPUT_HANDLE );

			GetConsoleScreenBufferInfo ( hConsole, &csbi );
			dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
			FillConsoleOutputCharacter ( hConsole, TEXT ( ' ' ), dwConSize,
										 coordScreen, &cCharsWritten );
			GetConsoleScreenBufferInfo ( hConsole, &csbi );
			FillConsoleOutputAttribute ( hConsole, csbi.wAttributes, dwConSize,
										 coordScreen, &cCharsWritten );
			SetConsoleCursorPosition ( hConsole, coordScreen );
		#elif defined ( TARGET_OS_MACOSX ) || defined ( TARGET_OS_LINUX ) || \
            defined ( TARGET_OS_NDSFIRMWARE )
			Write ( "%s", "\033[2J" );
		#endif
		}

		void
		Console::Flush ()
		{
			CoreIOReader::Flush();
			CoreIOWriter::Flush();
		}

		void
		Console::MoveUp ( int _lines )
		{
		#if defined ( TARGET_OS_WINDOWS )
			COORD coordScreen = { 0, 0 };
			CONSOLE_SCREEN_BUFFER_INFO csbi;
			HANDLE hConsole = GetStdHandle ( STD_OUTPUT_HANDLE );

			GetConsoleScreenBufferInfo ( hConsole, &csbi );
			coordScreen = csbi.dwCursorPosition;
			coordScreen.Y -= (short)_lines;
			if ( coordScreen.Y < 0 ) coordScreen.Y = 0;
			SetConsoleCursorPosition ( hConsole, coordScreen );
		#elif defined ( TARGET_OS_MACOSX ) || defined ( TARGET_OS_LINUX )
			Write ( "%s%d%s", "\033[", _lines, "A" );
		#endif
		}

		char Console::ReadChar ()
		{
			char _result = 0;
			fscanf ( m_fileInputPointer, "%c", &_result );
			CoreIOReader::Flush();
			return _result;
		}

		int Console::ReadInt ()
		{
			int _result = 0;
			fscanf ( m_fileInputPointer, "%d", &_result );
			CoreIOReader::Flush();
			return _result;
		}

		long Console::ReadLong ()
		{
			long _result = 0;
			fscanf ( m_fileInputPointer, "%ld", &_result );
			CoreIOReader::Flush();
			return _result;
		}

		float Console::ReadFloat ()
		{
			float _result = 0;
			fscanf ( m_fileInputPointer, "%f", &_result );
			CoreIOReader::Flush();
			return _result;
		}

		double Console::ReadDouble ()
		{
			double _result = 0;
			fscanf ( m_fileInputPointer, "%lf", &_result );
			CoreIOReader::Flush();
			return _result;
		}

		char Console::ReadChar ( char _min, char _max )
		{
			char _result = 0;
			fscanf ( m_fileInputPointer, "%c", &_result );
			CoreIOReader::Flush();
			if ( ( _min && _max ) && ( _min < _max ) )
			{
				if ( _result < _min )
					_result = _min;
				if ( _result > _max )
					_result = _max;
			}
			return _result;
		}

		int Console::ReadInt ( int _min, int _max )
		{
			int _result = 0;
			fscanf ( m_fileInputPointer, "%d", &_result );
			CoreIOReader::Flush();
			if ( ( _min && _max ) && ( _min < _max ) )
			{
				if ( _result < _min )
					_result = _min;
				if ( _result > _max )
					_result = _max;
			}
			return _result;
		}

		long Console::ReadLong ( long _min, long _max )
		{
			long _result = 0;
			fscanf ( m_fileInputPointer, "%ld", &_result );
			CoreIOReader::Flush();
			if ( ( _min && _max ) && ( _min < _max ) )
			{
				if ( _result < _min )
					_result = _min;
				if ( _result > _max )
					_result = _max;
			}
			return _result;
		}

		float Console::ReadFloat ( float _min, float _max )
		{
			float _result = 0;
			fscanf ( m_fileInputPointer, "%f", &_result );
			CoreIOReader::Flush();
			if ( ( _min && _max ) && ( _min < _max ) )
			{
				if ( _result < _min )
					_result = _min;
				if ( _result > _max )
					_result = _max;
			}
			return _result;
		}

		double Console::ReadDouble ( double _min, double _max )
		{
			double _result = 0;
			fscanf ( m_fileInputPointer, "%lf", &_result );
			CoreIOReader::Flush();
			if ( ( _min && _max ) && ( _min < _max ) )
			{
				if ( _result < _min )
					_result = _min;
				if ( _result > _max )
					_result = _max;
			}
			return _result;
		}

		int Console::Seek ( cc_int64_t _position ) { return 0; }
		int Console::Forward ( cc_int64_t _position ) { return 0; }
		cc_int64_t Console::Length() { return 0; }
		int Console::Read ( char *_buffer, size_t _bufferLength, size_t _bufferIndex, size_t _count ) { return 0; }
		bool Console::EndOfFile () { return false; }
	}
}
<commit_msg>Reset fixed.<commit_after>/*
 *   CrissCross
 *   A multi-purpose cross-platform library.
 *
 *   A product of Uplink Laboratories.
 *
 *   (c) 2006-2008 Steven Noonan.
 *   Licensed under the New BSD License.
 *
 */

#include <crisscross/universal_include.h>
#include <crisscross/debug.h>
#include <crisscross/console.h>

namespace CrissCross
{
	namespace IO
	{
		Console::Console ( bool _clearOnInit ):
		CoreIOWriter ( stdout, false, CC_LN_LF ),
		CoreIOReader ( stdin, false, CC_LN_LF )
		{
		#ifdef TARGET_OS_WINDOWS
			m_consoleAllocated = false;
			if ( AllocConsole () == TRUE )
			{
				m_consoleAllocated = true;
				int hCrt = _open_osfhandle ( ( intptr_t ) GetStdHandle ( STD_OUTPUT_HANDLE ), _O_TEXT );
				FILE *hf = _fdopen ( hCrt, "w" );

				*stdout = *hf;
				int i = setvbuf ( stdout, NULL, _IONBF, 0 );

				hCrt =
					_open_osfhandle ( ( intptr_t ) GetStdHandle ( STD_ERROR_HANDLE ),
									  _O_TEXT );
				hf = _fdopen ( hCrt, "w" );
				*stderr = *hf;
				i = setvbuf ( stdout, NULL, _IONBF, 0 );
			}

			if ( _clearOnInit ) Clear();

			SetTitle ( CC_LIB_NAME " " CC_LIB_VERSION " (Codename " CC_LIB_CODENAME ")" );
        #elif defined ( TARGET_OS_NDSFIRMWARE )
            irqInit();
            irqEnable(IRQ_VBLANK);
            videoSetMode(MODE_0_2D);
            videoSetModeSub(MODE_0_2D | DISPLAY_BG0_ACTIVE);
            vramSetBankC(VRAM_C_SUB_BG);
	        SUB_BG0_CR = BG_MAP_BASE(31);
	        BG_PALETTE_SUB[255] = RGB15(31,31,31);
	        consoleInitDefault((u16*)SCREEN_BASE_BLOCK_SUB(31), (u16*)CHAR_BASE_BLOCK_SUB(0), 16);
		#endif
		#ifdef ENABLE_CREDITS
        #if defined ( TARGET_OS_NDSFIRMWARE )
			g_stdout->SetColour ( g_stdout->FG_GREEN | g_stdout->FG_INTENSITY );
			g_stdout->WriteLine ( "Powered by " CC_LIB_NAME " v" CC_LIB_VERSION );
			g_stdout->SetColour ( 0 );
			g_stdout->WriteLine ( CC_LIB_NDS_COPYRIGHT );
			g_stdout->WriteLine ();
        #else
			g_stdout->SetColour ( g_stdout->FG_GREEN | g_stdout->FG_INTENSITY );
			g_stdout->WriteLine ( "Powered by " CC_LIB_NAME " " CC_LIB_VERSION " (Codename " CC_LIB_CODENAME ")\n    " CC_LIB_URL );
			g_stdout->SetColour ( 0 );
			g_stdout->WriteLine ( CC_LIB_COPYRIGHT );
			g_stdout->WriteLine ();
        #endif
		#endif
		}

		Console::Console ( FILE * _outputBuffer, FILE *_inputBuffer ):
		CoreIOWriter ( _outputBuffer, false, CC_LN_LF ),
		CoreIOReader ( _inputBuffer, false, CC_LN_LF )
		{
		}

		Console::~Console ()
		{
			SetColour ( 0 );
		#ifdef TARGET_OS_WINDOWS
			if ( m_consoleAllocated ) FreeConsole ();
		#endif
		}

		void
		Console::SetColour ()
		{
			SetColour ( 0 );
		}

		void
		Console::SetColour ( int _flags )
		{
			CoreAssert ( this != NULL );

		#if !defined ( ANSI_COLOUR ) && defined ( TARGET_OS_WINDOWS )
			HANDLE hConsole = GetStdHandle ( STD_OUTPUT_HANDLE );

			if ( _flags == 0 )
				SetConsoleTextAttribute ( hConsole, FG_GRAY );
			else
				SetConsoleTextAttribute ( hConsole, _flags );
		#elif defined ( ANSI_COLOUR )
			// Reset colours to defaults.
			Write ( "\033[0m" );

			if ( _flags == 0 )
				return;

			char codes[16];

			sprintf ( codes, "\033[" );

			if ( _flags & FG_INTENSITY )
				strcat ( codes, "1;" );
			if ( _flags & FG_RED )
				strcat ( codes, "31;" );
			if ( _flags & FG_GREEN )
				strcat ( codes, "32;" );
			if ( _flags & FG_BROWN )
				strcat ( codes, "33;" );
			if ( _flags & FG_BLUE )
				strcat ( codes, "34;" );
			if ( _flags & FG_MAGENTA )
				strcat ( codes, "35;" );
			if ( _flags & FG_CYAN )
				strcat ( codes, "36;" );
			if ( _flags & FG_GRAY )
				strcat ( codes, "37;" );
			if ( _flags & FG_WHITE )
				strcat ( codes, "39;" );

			/*
			   TODO: Determine if there is an ANSI code for background color intensity.
			   if ( _flags & BG_INTENSITY )
			   strcat ( codes, "???????" );
			 */
			if ( _flags & BG_RED )
				strcat ( codes, "41;" );
			if ( _flags & BG_GREEN )
				strcat ( codes, "42;" );
			if ( _flags & BG_BROWN )
				strcat ( codes, "43;" );
			if ( _flags & BG_BLUE )
				strcat ( codes, "44;" );
			if ( _flags & BG_MAGENTA )
				strcat ( codes, "45;" );
			if ( _flags & BG_CYAN )
				strcat ( codes, "46;" );
			if ( _flags & BG_WHITE )
				strcat ( codes, "47;" );

			codes[strlen ( codes ) - 1] = 'm';

			Write ( "%s", codes );
		#endif
		}

		void
		Console::SetTitle ( const char *_title )
		{
		#ifdef TARGET_OS_WINDOWS
			SetConsoleTitleA ( _title );
		#endif
		}

		void
		Console::SetTitle ( std::string &_title )
		{
			SetTitle ( _title.c_str () );
		}

		void
		Console::Clear ()
		{
			CoreAssert ( this != NULL );

		#if defined ( TARGET_OS_WINDOWS )
			COORD coordScreen = { 0, 0 };
			DWORD cCharsWritten;
			CONSOLE_SCREEN_BUFFER_INFO csbi;
			DWORD dwConSize;
			HANDLE hConsole = GetStdHandle ( STD_OUTPUT_HANDLE );

			GetConsoleScreenBufferInfo ( hConsole, &csbi );
			dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
			FillConsoleOutputCharacter ( hConsole, TEXT ( ' ' ), dwConSize,
										 coordScreen, &cCharsWritten );
			GetConsoleScreenBufferInfo ( hConsole, &csbi );
			FillConsoleOutputAttribute ( hConsole, csbi.wAttributes, dwConSize,
										 coordScreen, &cCharsWritten );
			SetConsoleCursorPosition ( hConsole, coordScreen );
		#elif defined ( TARGET_OS_MACOSX ) || defined ( TARGET_OS_LINUX ) || \
            defined ( TARGET_OS_NDSFIRMWARE )
			Write ( "%s", "\033[2J" );
		#endif
		}

		void
		Console::Flush ()
		{
			CoreIOReader::Flush();
			CoreIOWriter::Flush();
		}

		void
		Console::MoveUp ( int _lines )
		{
		#if defined ( TARGET_OS_WINDOWS )
			COORD coordScreen = { 0, 0 };
			CONSOLE_SCREEN_BUFFER_INFO csbi;
			HANDLE hConsole = GetStdHandle ( STD_OUTPUT_HANDLE );

			GetConsoleScreenBufferInfo ( hConsole, &csbi );
			coordScreen = csbi.dwCursorPosition;
			coordScreen.Y -= (short)_lines;
			if ( coordScreen.Y < 0 ) coordScreen.Y = 0;
			SetConsoleCursorPosition ( hConsole, coordScreen );
		#elif defined ( TARGET_OS_MACOSX ) || defined ( TARGET_OS_LINUX )
			Write ( "%s%d%s", "\033[", _lines, "A" );
		#endif
		}

		char Console::ReadChar ()
		{
			char _result = 0;
			fscanf ( m_fileInputPointer, "%c", &_result );
			CoreIOReader::Flush();
			return _result;
		}

		int Console::ReadInt ()
		{
			int _result = 0;
			fscanf ( m_fileInputPointer, "%d", &_result );
			CoreIOReader::Flush();
			return _result;
		}

		long Console::ReadLong ()
		{
			long _result = 0;
			fscanf ( m_fileInputPointer, "%ld", &_result );
			CoreIOReader::Flush();
			return _result;
		}

		float Console::ReadFloat ()
		{
			float _result = 0;
			fscanf ( m_fileInputPointer, "%f", &_result );
			CoreIOReader::Flush();
			return _result;
		}

		double Console::ReadDouble ()
		{
			double _result = 0;
			fscanf ( m_fileInputPointer, "%lf", &_result );
			CoreIOReader::Flush();
			return _result;
		}

		char Console::ReadChar ( char _min, char _max )
		{
			char _result = 0;
			fscanf ( m_fileInputPointer, "%c", &_result );
			CoreIOReader::Flush();
			if ( ( _min && _max ) && ( _min < _max ) )
			{
				if ( _result < _min )
					_result = _min;
				if ( _result > _max )
					_result = _max;
			}
			return _result;
		}

		int Console::ReadInt ( int _min, int _max )
		{
			int _result = 0;
			fscanf ( m_fileInputPointer, "%d", &_result );
			CoreIOReader::Flush();
			if ( ( _min && _max ) && ( _min < _max ) )
			{
				if ( _result < _min )
					_result = _min;
				if ( _result > _max )
					_result = _max;
			}
			return _result;
		}

		long Console::ReadLong ( long _min, long _max )
		{
			long _result = 0;
			fscanf ( m_fileInputPointer, "%ld", &_result );
			CoreIOReader::Flush();
			if ( ( _min && _max ) && ( _min < _max ) )
			{
				if ( _result < _min )
					_result = _min;
				if ( _result > _max )
					_result = _max;
			}
			return _result;
		}

		float Console::ReadFloat ( float _min, float _max )
		{
			float _result = 0;
			fscanf ( m_fileInputPointer, "%f", &_result );
			CoreIOReader::Flush();
			if ( ( _min && _max ) && ( _min < _max ) )
			{
				if ( _result < _min )
					_result = _min;
				if ( _result > _max )
					_result = _max;
			}
			return _result;
		}

		double Console::ReadDouble ( double _min, double _max )
		{
			double _result = 0;
			fscanf ( m_fileInputPointer, "%lf", &_result );
			CoreIOReader::Flush();
			if ( ( _min && _max ) && ( _min < _max ) )
			{
				if ( _result < _min )
					_result = _min;
				if ( _result > _max )
					_result = _max;
			}
			return _result;
		}

		int Console::Seek ( cc_int64_t _position ) { return 0; }
		int Console::Forward ( cc_int64_t _position ) { return 0; }
		cc_int64_t Console::Length() { return 0; }
		int Console::Read ( char *_buffer, size_t _bufferLength, size_t _bufferIndex, size_t _count ) { return 0; }
		bool Console::EndOfFile () { return false; }
	}
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <cmath>
#include "display.hpp"
#include "my_opengl.hpp"
#include "bind.hpp"
#include "math.hpp"
#include "logic.hpp"
#include "input.hpp"

static inline RenderContext contextFromFiles(std::string name)
{
  std::stringstream vert;
  std::stringstream frag;

  vert << std::ifstream("shaders/" + name + ".vert").rdbuf();
  frag << std::ifstream("shaders/" + name + ".frag").rdbuf();
  return {Vao(), my_opengl::createProgram<2>({GL_VERTEX_SHADER, GL_FRAGMENT_SHADER},
					     {vert.str(), frag.str()})};
}

Display::Display(Vect<2u, unsigned int> size, Logic &logic)
  : size(size), offset{0.0f, 0.0f}, scale{static_cast<float>(size[1]) / static_cast<float>(size[0]), 1.0f},
  worldRenderContext(contextFromFiles("basic")),
  lightRenderContext(contextFromFiles("color")),
  postProcessContext(contextFromFiles("multiply")),
  fixtureBuffer(),
  lightBuffer(),
  cornerBuffer(),
  lightRenderTexture(size),
  worldRenderTexture(size),
  lights(),
  fpsCounter(),
  logic(logic)
{
  {
    Bind<RenderContext> bind(worldRenderContext);
    float const data[12]{0.5f, 0.5f, 1.0f, 0.0f,
	0.0f, -0.7f, 1.0f, 1.0f,
	-0.5f, 0.5f, 0.0f, 1.0f};

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER, fixtureBuffer);
    glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(float), data, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 2, GL_FLOAT, false, 4 * sizeof(float), nullptr);
    glVertexAttribPointer(1, 2, GL_FLOAT, false, 4 * sizeof(float), reinterpret_cast<void *>(2u * sizeof(float)));
  }
  {
    Bind<RenderContext> bind(lightRenderContext);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER, lightBuffer);
    glVertexAttribPointer(0, 2, GL_FLOAT, false, 6 * sizeof(float), nullptr);
    glVertexAttribPointer(1, 4, GL_FLOAT, false, 6 * sizeof(float), reinterpret_cast<void *>(2u * sizeof(float)));
  }
  {
    Bind<RenderContext> bind(postProcessContext);
    float const data[8]{0.0f, 0.0f,
	0.0f, 1.0f,
	1.0f, 0.0f,
	1.0f, 1.0f};

    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, cornerBuffer);
    glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(float), data, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 2, GL_FLOAT, false, 2 * sizeof(float), nullptr);
  }
  lights.push_back({{0.5f, 0.0f}, {1.0f, 0.5f, 1.0f, 1.0f}, 1.5f});
  lights.push_back({{-0.5f, 0.0f}, {0.0f, 1.0f, 0.5f, 1.0f}, 0.5f});
}

Display::~Display()
{
  lights.clear();
}

void Display::setOffsetAndScale(Program program)
{
  my_opengl::setUniform(offset, "offset", program);
  my_opengl::setUniform(scale, "scale", program);
}

//TODO : optimize
void Display::renderLights()
{
  Bind<RenderContext> bind(lightRenderContext);
  float *data(new float[lights.size() * 6u  * 3u * 20u]);
  unsigned int i(0);

  std::for_each(lights.begin(), lights.end(),
		[&data, &i](Light l)
		{
		  for (unsigned int j(0); j < 20u; j++)
		    {
		      data[i++] = l.center[0];
		      data[i++] = l.center[1];
		      data[i++] = l.color[0];
		      data[i++] = l.color[1];
		      data[i++] = l.color[2];
		      data[i++] = l.color[3];
		      data[i++] = l.center[0] + cos(static_cast<float>(j) / 20.0f * M_PI * 2.0f) * l.radius;
		      data[i++] = l.center[1] + sin(static_cast<float>(j) / 20.0f * M_PI * 2.0f) * l.radius;
		      data[i++] = 0.0f;
		      data[i++] = 0.0f;
		      data[i++] = 0.0f;
		      data[i++] = 0.0f;
		      data[i++] = l.center[0] + cos(static_cast<float>(j + 1) / 20.0f * M_PI * 2.0f) * l.radius;
		      data[i++] = l.center[1] + sin(static_cast<float>(j + 1) / 20.0f * M_PI * 2.0f) * l.radius;
		      data[i++] = 0.0f;
		      data[i++] = 0.0f;
		      data[i++] = 0.0f;
		      data[i++] = 0.0f;
		    }
		});
  glBindBuffer(GL_ARRAY_BUFFER, lightBuffer);
  glBufferData(GL_ARRAY_BUFFER, i * sizeof(float), data, GL_STATIC_DRAW);
  delete [] data;
  setOffsetAndScale(lightRenderContext.program);
  glBindFramebuffer(GL_FRAMEBUFFER, lightRenderTexture.framebuffer);
  glClearColor(0.1f, 0.1f, 0.1f, 0.0f);
  glClear(GL_COLOR_BUFFER_BIT);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glEnable(GL_BLEND);
  glDrawArrays(GL_TRIANGLES, 0, i / 6u);
  glBindFramebuffer(GL_FRAMEBUFFER, 0);
  glDisable(GL_BLEND);
}

void Display::displayBots()
{
  Bind<RenderContext> bind(worldRenderContext);
  float *data = new float[logic.getNanoBots().size() * 4 * 4 * 3];
  unsigned int i(0);

  for (unsigned int j(0); j < logic.getNanoBots().size(); j++)
    {
      Vect<2u, double> d(logic.getNanoBots()[j]->getSpeed().normalized() * 0.01);

      data[i++] = logic.getNanoBots()[j]->getPos()[0] + d[0];
      data[i++] = logic.getNanoBots()[j]->getPos()[1] + d[1];
      data[i++] = 1.0f;
      data[i++] = 1.0f;
      data[i++] = logic.getNanoBots()[j]->getPos()[0] + d[1] - d[0];
      data[i++] = logic.getNanoBots()[j]->getPos()[1] - d[0] - d[1];
      data[i++] = 0.0f;
      data[i++] = 1.0f;
      data[i++] = logic.getNanoBots()[j]->getPos()[0] - d[1] - d[0];
      data[i++] = logic.getNanoBots()[j]->getPos()[1] + d[0] - d[1];
      data[i++] = 1.0f;
      data[i++] = 0.0f;
    }
  glBindBuffer(GL_ARRAY_BUFFER, fixtureBuffer);
  glBufferData(GL_ARRAY_BUFFER, i * sizeof(float), data, GL_STATIC_DRAW);
  delete [] data;
  setOffsetAndScale(worldRenderContext.program);
  glBindFramebuffer(GL_FRAMEBUFFER, worldRenderTexture.framebuffer);
  glClearColor(0.1f, 0.1f, 0.1f, 0.0f);
  glClear(GL_COLOR_BUFFER_BIT);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glEnable(GL_BLEND);
  glDrawArrays(GL_TRIANGLES, 0, i / 4);
  glBindFramebuffer(GL_FRAMEBUFFER, 0);
  glDisable(GL_BLEND);
}

void Display::displayMouseSelection()
{
  if (!Callback::leftPressed)
    return;

  glClear(GL_COLOR_BUFFER_BIT);
  glLineWidth(30);
  glFlush();
}

void Display::postProcess()
{
  Bind<RenderContext> bind(postProcessContext);

  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, lightRenderTexture.texture);
  glActiveTexture(GL_TEXTURE1);
  glBindTexture(GL_TEXTURE_2D, worldRenderTexture.texture);
  my_opengl::setUniform(0u, "lights", postProcessContext.program);
  my_opengl::setUniform(1u, "world", postProcessContext.program);
  my_opengl::setUniform(Vect<2u, float>{1.0f, 1.0f} / Vect<2u, float>(size), "step", postProcessContext.program);
  glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}

void Display::render()
{
  // lights[0].center += {-0.01, 0.01};
  //  lights[0].center[0] -= 0.01;
  renderLights();
  displayBots();
  // TODO : good idea ?
  displayMouseSelection();
  postProcess();
  fpsCounter.tick();
}
<commit_msg>deisplay of drag select<commit_after>#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <cmath>
#include "display.hpp"
#include "my_opengl.hpp"
#include "bind.hpp"
#include "math.hpp"
#include "logic.hpp"
#include "input.hpp"

static inline RenderContext contextFromFiles(std::string name)
{
  std::stringstream vert;
  std::stringstream frag;

  vert << std::ifstream("shaders/" + name + ".vert").rdbuf();
  frag << std::ifstream("shaders/" + name + ".frag").rdbuf();
  return {Vao(), my_opengl::createProgram<2>({GL_VERTEX_SHADER, GL_FRAGMENT_SHADER},
					     {vert.str(), frag.str()})};
}

Display::Display(Vect<2u, unsigned int> size, Logic &logic)
  : size(size), offset{0.0f, 0.0f}, scale{static_cast<float>(size[1]) / static_cast<float>(size[0]), 1.0f},
  worldRenderContext(contextFromFiles("basic")),
  lightRenderContext(contextFromFiles("color")),
  postProcessContext(contextFromFiles("multiply")),
  fixtureBuffer(),
  lightBuffer(),
  cornerBuffer(),
  lightRenderTexture(size),
  worldRenderTexture(size),
  lights(),
  fpsCounter(),
  logic(logic)
{
  {
    Bind<RenderContext> bind(worldRenderContext);
    // float const data[12]{0.5f, 0.5f, 1.0f, 0.0f,
    // 	0.0f, -0.7f, 1.0f, 1.0f,
    // 	-0.5f, 0.5f, 0.0f, 1.0f};

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER, fixtureBuffer);
    //    glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(float), data, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 2, GL_FLOAT, false, 5 * sizeof(float), nullptr);
    glVertexAttribPointer(1, 3, GL_FLOAT, false, 5 * sizeof(float), reinterpret_cast<void *>(2u * sizeof(float)));
  }
  {
    Bind<RenderContext> bind(lightRenderContext);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER, lightBuffer);
    glVertexAttribPointer(0, 2, GL_FLOAT, false, 6 * sizeof(float), nullptr);
    glVertexAttribPointer(1, 4, GL_FLOAT, false, 6 * sizeof(float), reinterpret_cast<void *>(2u * sizeof(float)));
  }
  {
    Bind<RenderContext> bind(postProcessContext);
    float const data[8]{0.0f, 0.0f,
	0.0f, 1.0f,
	1.0f, 0.0f,
	1.0f, 1.0f};

    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, cornerBuffer);
    glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(float), data, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 2, GL_FLOAT, false, 2 * sizeof(float), nullptr);
  }
  lights.push_back({{0.5f, 0.0f}, {1.0f, 0.5f, 1.0f, 1.0f}, 1.5f});
  lights.push_back({{-0.5f, 0.0f}, {0.0f, 1.0f, 0.5f, 1.0f}, 0.5f});
}

Display::~Display()
{
  lights.clear();
}

void Display::setOffsetAndScale(Program program)
{
  my_opengl::setUniform(offset, "offset", program);
  my_opengl::setUniform(scale, "scale", program);
}

//TODO : optimize
void Display::renderLights()
{
  Bind<RenderContext> bind(lightRenderContext);
  float *data(new float[lights.size() * 6u  * 3u * 20u]);
  unsigned int i(0);

  std::for_each(lights.begin(), lights.end(),
		[&data, &i](Light l)
		{
		  for (unsigned int j(0); j < 20u; j++)
		    {
		      data[i++] = l.center[0];
		      data[i++] = l.center[1];
		      data[i++] = l.color[0];
		      data[i++] = l.color[1];
		      data[i++] = l.color[2];
		      data[i++] = l.color[3];
		      data[i++] = l.center[0] + cos(static_cast<float>(j) / 20.0f * M_PI * 2.0f) * l.radius;
		      data[i++] = l.center[1] + sin(static_cast<float>(j) / 20.0f * M_PI * 2.0f) * l.radius;
		      data[i++] = 0.0f;
		      data[i++] = 0.0f;
		      data[i++] = 0.0f;
		      data[i++] = 0.0f;
		      data[i++] = l.center[0] + cos(static_cast<float>(j + 1) / 20.0f * M_PI * 2.0f) * l.radius;
		      data[i++] = l.center[1] + sin(static_cast<float>(j + 1) / 20.0f * M_PI * 2.0f) * l.radius;
		      data[i++] = 0.0f;
		      data[i++] = 0.0f;
		      data[i++] = 0.0f;
		      data[i++] = 0.0f;
		    }
		});
  glBindBuffer(GL_ARRAY_BUFFER, lightBuffer);
  glBufferData(GL_ARRAY_BUFFER, i * sizeof(float), data, GL_STATIC_DRAW);
  delete [] data;
  setOffsetAndScale(lightRenderContext.program);
  glBindFramebuffer(GL_FRAMEBUFFER, lightRenderTexture.framebuffer);
  glClearColor(0.1f, 0.1f, 0.1f, 0.0f);
  glClear(GL_COLOR_BUFFER_BIT);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glEnable(GL_BLEND);
  glDrawArrays(GL_TRIANGLES, 0, i / 6u);
  glBindFramebuffer(GL_FRAMEBUFFER, 0);
  glDisable(GL_BLEND);
}

void Display::displayBots()
{
  Bind<RenderContext> bind(worldRenderContext);
  float *data = new float[logic.getNanoBots().size() * 4 * 5 * 3];
  unsigned int i(0);

  for (unsigned int j(0); j < logic.getNanoBots().size(); j++)
    {
      Vect<2u, double> d(logic.getNanoBots()[j]->getSpeed().normalized() * 0.01);

      data[i++] = logic.getNanoBots()[j]->getPos()[0] + d[0];
      data[i++] = logic.getNanoBots()[j]->getPos()[1] + d[1];
      data[i++] = 1.0f;
      data[i++] = 1.0f;
      data[i++] = 1.0f;
      data[i++] = logic.getNanoBots()[j]->getPos()[0] + d[1] - d[0];
      data[i++] = logic.getNanoBots()[j]->getPos()[1] - d[0] - d[1];
      data[i++] = 0.0f;
      data[i++] = 1.0f;
      data[i++] = 1.0f;
      data[i++] = logic.getNanoBots()[j]->getPos()[0] - d[1] - d[0];
      data[i++] = logic.getNanoBots()[j]->getPos()[1] + d[0] - d[1];
      data[i++] = 1.0f;
      data[i++] = 0.0f;
      data[i++] = 1.0f;
    }
  glBindBuffer(GL_ARRAY_BUFFER, fixtureBuffer);
  glBufferData(GL_ARRAY_BUFFER, i * sizeof(float), data, GL_STATIC_DRAW);
  delete [] data;
  setOffsetAndScale(worldRenderContext.program);
  glBindFramebuffer(GL_FRAMEBUFFER, worldRenderTexture.framebuffer);
  // glClearColor(0.1f, 0.1f, 0.1f, 0.0f);
  // glClear(GL_COLOR_BUFFER_BIT);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glEnable(GL_BLEND);
  glDrawArrays(GL_TRIANGLES, 0, i / 5);
  glBindFramebuffer(GL_FRAMEBUFFER, 0);
  glDisable(GL_BLEND);
}

void Display::displayMouseSelection()
{
  Bind<RenderContext> bind(worldRenderContext);
  glBindFramebuffer(GL_FRAMEBUFFER, worldRenderTexture.framebuffer);
  glClearColor(0.1f, 0.1f, 0.1f, 0.0f);
  glClear(GL_COLOR_BUFFER_BIT);
  if (!Callback::leftPressed)
    return;
  float data[4 * 5 * 4];
  unsigned int i(0);

  for (unsigned int j(0); j < 4; j++)
    {
      Vect<2u, double> d(logic.getNanoBots()[j]->getSpeed().normalized() * 0.01);

      data[i++] = (j == 1 || j == 2) ? Callback::dragOrigin[0] : Callback::pos[0];
      data[i++] = (j <= 1) ? Callback::dragOrigin[1] : Callback::pos[1];
      std::cout << Callback::dragOrigin[0] << std::endl;
      data[i++] = 1.0f;
      data[i++] = 1.0f;
      data[i++] = 1.0f;
    }
  glBindBuffer(GL_ARRAY_BUFFER, fixtureBuffer);
  glBufferData(GL_ARRAY_BUFFER, i * sizeof(float), data, GL_STATIC_DRAW);
  setOffsetAndScale(worldRenderContext.program);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  glEnable(GL_BLEND);
  glDrawArrays(GL_LINE_LOOP, 0, 4);
  glBindFramebuffer(GL_FRAMEBUFFER, 0);
  glDisable(GL_BLEND);
}

void Display::postProcess()
{
  Bind<RenderContext> bind(postProcessContext);

  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, lightRenderTexture.texture);
  glActiveTexture(GL_TEXTURE1);
  glBindTexture(GL_TEXTURE_2D, worldRenderTexture.texture);
  my_opengl::setUniform(0u, "lights", postProcessContext.program);
  my_opengl::setUniform(1u, "world", postProcessContext.program);
  my_opengl::setUniform(Vect<2u, float>{1.0f, 1.0f} / Vect<2u, float>(size), "step", postProcessContext.program);
  glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}

void Display::render()
{
  // lights[0].center += {-0.01, 0.01};
  //  lights[0].center[0] -= 0.01;
  renderLights();
  displayMouseSelection();
  displayBots();
  // TODO : good idea ?
  postProcess();
  fpsCounter.tick();
}
<|endoftext|>


<commit_before>#include <fstream>
#include "files.hpp"
#include "vfs.hpp"

namespace MgCore
{
	std::string read_file(std::string filename)
        {
                std::ifstream in(filename, std::ios::in | std::ios_base::ate);
                if (in) {
                        std::string contents;
                        contents.resize(in.tellg());
                        in.seekg(0, std::ios::beg);
                        in.read(&contents[0], contents.size());
                        in.close();
                        return contents;
                } else {
                        return "";
                }
        }

	std::string vfs_read_file(std::string filename)
	{
		ttvfs::File *vf = VFS.GetFile( filename.c_str() );

		if ( vf && vf->open("r") ) {
			std::string contents;
			char buff[vf->size()];
			size_t len = vf->read(buff, sizeof(buff));
			vf->close();
			contents = buff;
			return contents;
		} else {
			return "";
		}
	}
}
<commit_msg>Simplified vfs_read_file.<commit_after>#include <fstream>
#include "files.hpp"
#include "vfs.hpp"

namespace MgCore
{
	std::string read_file(std::string filename)
    {
        std::ifstream in(filename, std::ios::in | std::ios_base::ate);
        if (in) {
            std::string contents;
            contents.resize(in.tellg());
            in.seekg(0, std::ios::beg);
            in.read(&contents[0], contents.size());
            in.close();
            return contents;
        } else {
        	return "";
		}
	}

	std::string vfs_read_file(std::string filename)
	{
		ttvfs::File *vf = VFS.GetFile( filename.c_str() );

		if ( vf && vf->open("r") ) {
			std::string contents;
			contents.resize( vf->size() );
			vf->read(&contents[0], contents.size());
			vf->close();
			return contents;
		} else {
			return "";
		}
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: gcach_vdev.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hdu $ $Date: 2001-02-15 16:08:32 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <glyphcache.hxx>

// -----------------------------------------------------------------------

class VirtDevServerFont : public ServerFont
{
public:
    virtual bool                    GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const;
    virtual bool                    GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const;
    virtual bool                    GetGlyphOutline( int nGlyphIndex, PolyPolygon& ) const;

protected:
friend GlyphCache;
    static long                 FetchFontList( ImplDevFontList* );
    static void                 ClearFontList();

    static VirtDevServerFont*   CreateFont( const ImplFontSelectData& );
    virtual void                    FetchFontMetric( ImplFontMetricData&, long& rFactor ) const;
    virtual ULONG               GetKernPairs( ImplKernPairData** ) const;

    virtual int                 GetGlyphIndex( sal_Unicode ) const;
    virtual void                    InitGlyphData( int nGlyphIndex, GlyphData& ) const;

private:
                                VirtDevServerFont( const ImplFontSelectData& );
};

// -----------------------------------------------------------------------
<commit_msg>add GetAntialiasAdvice() and reformatting<commit_after>/*************************************************************************
 *
 *  $RCSfile: gcach_vdev.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hdu $ $Date: 2001-03-30 12:20:56 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <glyphcache.hxx>

// -----------------------------------------------------------------------

class VirtDevServerFont : public ServerFont
{
public:
    virtual bool                GetAntialiasAdvice( void ) const;
    virtual bool                GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const;
    virtual bool                GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const;
    virtual bool                GetGlyphOutline( int nGlyphIndex, PolyPolygon& ) const;

protected:
friend GlyphCache;
    static long                 FetchFontList( ImplDevFontList* );
    static void                 ClearFontList();

    static VirtDevServerFont*   CreateFont( const ImplFontSelectData& );
    virtual void                FetchFontMetric( ImplFontMetricData&, long& rFactor ) const;
    virtual ULONG               GetKernPairs( ImplKernPairData** ) const;

    virtual int                 GetGlyphIndex( sal_Unicode ) const;
    virtual void                InitGlyphData( int nGlyphIndex, GlyphData& ) const;

private:
                                VirtDevServerFont( const ImplFontSelectData& );
};

// -----------------------------------------------------------------------
<|endoftext|>


<commit_before>//====== Copyright (c) 2012, Valve Corporation, All rights reserved. ========//
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//===========================================================================//

#include "demofiledump.h"

// these settings cause it to output nothing
bool g_bDumpGameEvents = false;
bool g_bSupressFootstepEvents = true;
bool g_bShowExtraPlayerInfoInGameEvents = false;
bool g_bDumpDeaths = false;
bool g_bSupressWarmupDeaths = true;
bool g_bDumpStringTables = false;
bool g_bDumpDataTables = false;
bool g_bDumpPacketEntities = false;
bool g_bDumpNetMessages = false;

int main( int argc, char *argv[] )
{
	CDemoFileDump DemoFileDump;

	if ( argc <= 1 )
	{
		printf( "demoinfogo filename.dem\n" );
		printf( "optional arguments:\n" \
				" -gameevents    Dump out game events.\n" \
				" -nofootsteps   Skip footstep events when dumping out game events.\n" \
				"                Should be after -gameevents.\n" \
				" -extrainfo     Show extra player info when dumping out game events.\n" \
				"                Should be after -gameevents.\n" \
				" -deathscsv     Dump out player death info in CSV form.\n" \
				" -nowarmup      Skip deaths during warm up when dumping player deaths.\n" \
				"                Should be after -deaths.\n" \
				" -stringtables  Dump string tables.\n" \
				" -datatables    Dump data tables. (send tables)\n" \
				" -packetentites Dump Packet Entities messages.\n" \
				" -netmessages   Dump net messages that are not one of the above.\n" \
				"Note: by default everything is dumped out.\n" );
		exit( 0 );
	}

	int nFileArgument = 1;
	if ( argc > 2 )
	{
		for ( int i = 1; i < argc; i++ )
		{
			// arguments start with - or /
			if ( argv[i][0] == '-' || argv[i][0] == '/' )
			{
				if ( strcasecmp( &argv[i][1], "gameevents" ) == 0 )
				{
					g_bDumpGameEvents = true;
					g_bSupressFootstepEvents = false;
					g_bShowExtraPlayerInfoInGameEvents = false;
				}
				else if ( strcasecmp( &argv[i][1], "nofootsteps" ) == 0 )
				{
					g_bSupressFootstepEvents = true;
				}
				else if ( strcasecmp( &argv[i][1], "extrainfo" ) == 0 )
				{
					g_bShowExtraPlayerInfoInGameEvents = true;
				}
				else if ( strcasecmp( &argv[i][1], "deathscsv" ) == 0 )
				{
					g_bDumpDeaths = true;
					g_bSupressWarmupDeaths = false;
				}
				else if ( strcasecmp( &argv[i][1], "nowarmup" ) == 0 )
				{
					g_bSupressWarmupDeaths = true;
				}
				else if ( strcasecmp( &argv[i][1], "stringtables" ) == 0 )
				{
					g_bDumpStringTables = true;
				}
				else if ( strcasecmp( &argv[i][1], "datatables" ) == 0 )
				{
					g_bDumpDataTables = true;
				}
				else if ( strcasecmp( &argv[i][1], "packetentities" ) == 0 )
				{
					g_bDumpPacketEntities = true;
				}
				else if ( strcasecmp( &argv[i][1], "netmessages" ) == 0 )
				{
					g_bDumpNetMessages = true;
				}
			}
			else
			{
				nFileArgument = i;
			}
		}
	}
	else
	{
		// default is to dump out everything
		g_bDumpGameEvents = true;
		g_bSupressFootstepEvents = false;
		g_bShowExtraPlayerInfoInGameEvents = true;
		g_bDumpDeaths = true;
		g_bSupressWarmupDeaths = false;
		g_bDumpStringTables = true;
		g_bDumpDataTables = true;
		g_bDumpPacketEntities = true;
		g_bDumpNetMessages = true;
	}

	if( DemoFileDump.Open( argv[ nFileArgument ] ) )
	{
		DemoFileDump.DoDump();
	}

	return 1;
}
<commit_msg>Don't always return 1. Fixes #21<commit_after>//====== Copyright (c) 2012, Valve Corporation, All rights reserved. ========//
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//===========================================================================//

#include "demofiledump.h"

// these settings cause it to output nothing
bool g_bDumpGameEvents = false;
bool g_bSupressFootstepEvents = true;
bool g_bShowExtraPlayerInfoInGameEvents = false;
bool g_bDumpDeaths = false;
bool g_bSupressWarmupDeaths = true;
bool g_bDumpStringTables = false;
bool g_bDumpDataTables = false;
bool g_bDumpPacketEntities = false;
bool g_bDumpNetMessages = false;

int main( int argc, char *argv[] )
{
	CDemoFileDump DemoFileDump;

	if ( argc <= 1 )
	{
		printf( "demoinfogo filename.dem\n" );
		printf( "optional arguments:\n" \
				" -gameevents    Dump out game events.\n" \
				" -nofootsteps   Skip footstep events when dumping out game events.\n" \
				"                Should be after -gameevents.\n" \
				" -extrainfo     Show extra player info when dumping out game events.\n" \
				"                Should be after -gameevents.\n" \
				" -deathscsv     Dump out player death info in CSV form.\n" \
				" -nowarmup      Skip deaths during warm up when dumping player deaths.\n" \
				"                Should be after -deaths.\n" \
				" -stringtables  Dump string tables.\n" \
				" -datatables    Dump data tables. (send tables)\n" \
				" -packetentites Dump Packet Entities messages.\n" \
				" -netmessages   Dump net messages that are not one of the above.\n" \
				"Note: by default everything is dumped out.\n" );
		exit( 0 );
	}

	int nFileArgument = 1;
	if ( argc > 2 )
	{
		for ( int i = 1; i < argc; i++ )
		{
			// arguments start with - or /
			if ( argv[i][0] == '-' || argv[i][0] == '/' )
			{
				if ( strcasecmp( &argv[i][1], "gameevents" ) == 0 )
				{
					g_bDumpGameEvents = true;
					g_bSupressFootstepEvents = false;
					g_bShowExtraPlayerInfoInGameEvents = false;
				}
				else if ( strcasecmp( &argv[i][1], "nofootsteps" ) == 0 )
				{
					g_bSupressFootstepEvents = true;
				}
				else if ( strcasecmp( &argv[i][1], "extrainfo" ) == 0 )
				{
					g_bShowExtraPlayerInfoInGameEvents = true;
				}
				else if ( strcasecmp( &argv[i][1], "deathscsv" ) == 0 )
				{
					g_bDumpDeaths = true;
					g_bSupressWarmupDeaths = false;
				}
				else if ( strcasecmp( &argv[i][1], "nowarmup" ) == 0 )
				{
					g_bSupressWarmupDeaths = true;
				}
				else if ( strcasecmp( &argv[i][1], "stringtables" ) == 0 )
				{
					g_bDumpStringTables = true;
				}
				else if ( strcasecmp( &argv[i][1], "datatables" ) == 0 )
				{
					g_bDumpDataTables = true;
				}
				else if ( strcasecmp( &argv[i][1], "packetentities" ) == 0 )
				{
					g_bDumpPacketEntities = true;
				}
				else if ( strcasecmp( &argv[i][1], "netmessages" ) == 0 )
				{
					g_bDumpNetMessages = true;
				}
			}
			else
			{
				nFileArgument = i;
			}
		}
	}
	else
	{
		// default is to dump out everything
		g_bDumpGameEvents = true;
		g_bSupressFootstepEvents = false;
		g_bShowExtraPlayerInfoInGameEvents = true;
		g_bDumpDeaths = true;
		g_bSupressWarmupDeaths = false;
		g_bDumpStringTables = true;
		g_bDumpDataTables = true;
		g_bDumpPacketEntities = true;
		g_bDumpNetMessages = true;
	}

	if( DemoFileDump.Open( argv[ nFileArgument ] ) )
	{
		DemoFileDump.DoDump();
	}

	return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <folly/experimental/coro/detail/Malloc.h>

#include <folly/BenchmarkUtil.h>

#include <new>

extern "C" {

FOLLY_NOINLINE
void* folly_coro_async_malloc(std::size_t size) {
  void* p = ::operator new(size);

  // Add this after the call to prevent the compiler from
  // turning the call to operator new() into a tailcall.
  folly::doNotOptimizeAway(p);

  return p;
}

FOLLY_NOINLINE
void folly_coro_async_free(void* ptr, std::size_t size) {
#if __cpp_sized_deallocation >= 201309
  ::operator delete(ptr, size);
#else
  // sized delete is not available on iOS before 10.0
  (void)size;
  ::operator delete(ptr);
#endif

  // Add this after the call to prevent the compiler from
  // turning the call to operator delete() into a tailcall.
  folly::doNotOptimizeAway(size);
}
} // extern "C"
<commit_msg>let coro malloc/free use wrappers<commit_after>/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <folly/experimental/coro/detail/Malloc.h>

#include <folly/BenchmarkUtil.h>
#include <folly/lang/New.h>

extern "C" {

FOLLY_NOINLINE
void* folly_coro_async_malloc(std::size_t size) {
  auto p = folly::operator_new(size);

  // Add this after the call to prevent the compiler from
  // turning the call to operator new() into a tailcall.
  folly::doNotOptimizeAway(p);

  return p;
}

FOLLY_NOINLINE
void folly_coro_async_free(void* ptr, std::size_t size) {
  folly::operator_delete(ptr, size);

  // Add this after the call to prevent the compiler from
  // turning the call to operator delete() into a tailcall.
  folly::doNotOptimizeAway(size);
}
} // extern "C"
<|endoftext|>