<commit_before>/*
	docker-script: run script files inside Docker containers
	Copyright (c) 2017, Adam Rehn

	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.

*/
#include "NvidiaDockerImages.h"
#include "Utility.h"
#include <stdexcept>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
using std::ifstream;
using std::vector;
using std::clog;
using std::endl;

//The different versions of docker we support
#define VANILLA_DOCKER "docker"
#define NVIDIA_DOCKER  "nvidia-docker"

int main (int argc, char* argv[])
{
	//Check that a script file was specified
	if (argc > 1)
	{
		try
		{
			//Parse CLI arguments, keeping docker-script options separate from script options
			string docker = VANILLA_DOCKER;
			bool interactive = true;
			bool verboseOutput = false;
			bool enableDebugging = false;
			bool dryrun = false;
			string trailingArgs = "";
			for (int i = 2; i < argc; ++i)
			{
				string currArg = string(argv[i]);
				if (currArg == "---verbose") {
					verboseOutput = true;
				}
				else if (currArg == "---debug") {
					enableDebugging = true;
				}
				else if (currArg == "---non-interactive") {
					interactive = false;
				}
				else if (currArg == "---nvidia-docker") {
					docker = NVIDIA_DOCKER;
				}
				else if (currArg == "---dry-run") {
					dryrun = true;
				}
				else {
					trailingArgs += "\"" + currArg + "\" ";
				}
			}

			//Attempt to open the script file
			string scriptPath = argv[1];
			ifstream script(scriptPath.c_str());
			if (script.is_open() == false) {
				throw std::runtime_error("failed to open script file \"" + scriptPath + "\"");
			}

			//Attempt to read the second shebang line in the script file
			string shebang = "";
			std::getline(script, shebang);
			std::getline(script, shebang);
			if (script.fail()) {
				throw std::runtime_error("failed to read second shebang line from \"" + scriptPath + "\"");
			}

			//Verify that the shebang line is well-formed
			size_t spacePos = shebang.find(" ");
			if (shebang.substr(0,2) != "#!" || spacePos == string::npos) {
				throw std::runtime_error("invalid second shebang line in script file \"" + scriptPath + "\"");
			}

			//Parse the shebang line
			string dockerImage = shebang.substr(2, spacePos - 2);
			string interpreter = shebang.substr(spacePos + 1);

			//Determine the full path to the script file
			scriptPath = Utility::realPath(scriptPath);

			//Extract the directory and filename components of the script's path, as well as our current working directory
			string scriptFile = Utility::baseName(scriptPath);
			string scriptDir  = Utility::dirName(scriptPath);
			string workingDir = Utility::cwd();

			//Extract the docker image name, without trailing tag name
			string imageWithoutTag = dockerImage.substr(0, dockerImage.find(":"));

			//If the specified docker image (or the specific image and tag combination) requires
			//nvidia-docker, we invoke nvidia-docker instead of regular docker
			auto nvDockerImages = NvidiaDockerImages::getList();
			if (Utility::contains(nvDockerImages, imageWithoutTag) || Utility::contains(nvDockerImages, dockerImage)) {
				docker = NVIDIA_DOCKER;
			}

			//If we were invoked using the symlink `nvidia-docker-script`, always use `nvidia-docker`
			if (string(argv[0]) == "nvidia-docker-script") {
				docker = NVIDIA_DOCKER;
			}

			//Build the `docker run` command
			string command = docker + " run " +
				string("\"-v") + scriptDir + ":/scriptdir\" " +
				string("\"-v") + workingDir + ":/workingdir\" " +
				string((enableDebugging == true) ? "--privileged=true " : "") +
				string("--workdir=/workingdir ") +
				string("-e \"HOST_CWD=") + workingDir + "\" " +
				string((interactive == true) ? "-ti " : "-t ") +
				string("--rm --entrypoint=\"\" ") +
				string("\"") + dockerImage + "\" " +
				string("\"") + interpreter + "\" " +
				string("\"/scriptdir/") + scriptFile + "\" " + trailingArgs;

			//If verbose output was requested, display diagnostic information
			if (verboseOutput == true)
			{
				clog << "Docker image:       " << dockerImage << endl;
				clog << "Interpreter:        " << interpreter << endl;
				clog << "Script path:        " << scriptPath << endl;
				clog << "Script basename:    " << scriptFile << endl;
				clog << "Script dirname:     " << scriptDir << endl;
				clog << "Working directory:  " << workingDir << endl;
				clog << "Trailing arguments: " << trailingArgs << endl;
				clog << endl << "Docker command:" << endl << command << endl << endl;
			}

			//If we are performing a dry run, simply print the command that would have been invoked
			if (dryrun == true) {
				std::cout << command << std::endl;
			}
			else
			{
				//Invoke docker
				return system(command.c_str());
			}
		}
		catch (std::runtime_error& e)
		{
			clog << "Error: " << e.what() << endl << endl;
			return 1;
		}
	}
	else
	{
		clog << "Usage:" << endl << argv[0] << " <SCRIPT> [---verbose] [---debug] [args for script]" << endl << endl;
		clog << "The first line of the script file should be a normal Unix shebang line." << endl;
		clog << "The second line of the script file should be:" << endl;
		clog << "#!<IMAGE> <INTERPRETER>" << endl << endl;
	}

	return 0;
}
<commit_msg>Add flag to specify container name<commit_after>/*
	docker-script: run script files inside Docker containers
	Copyright (c) 2017, Adam Rehn

	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.

*/
#include "NvidiaDockerImages.h"
#include "Utility.h"
#include <stdexcept>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
using std::ifstream;
using std::vector;
using std::clog;
using std::endl;

//The different versions of docker we support
#define VANILLA_DOCKER "docker"
#define NVIDIA_DOCKER  "nvidia-docker"

int main (int argc, char* argv[])
{
	//Check that a script file was specified
	if (argc > 1)
	{
		try
		{
			//Parse CLI arguments, keeping docker-script options separate from script options
			string docker = VANILLA_DOCKER;
			string name = "";
			bool interactive = true;
			bool verboseOutput = false;
			bool enableDebugging = false;
			bool dryrun = false;
			string trailingArgs = "";
			for (int i = 2; i < argc; ++i)
			{
				string currArg = string(argv[i]);
				if (currArg == "---verbose") {
					verboseOutput = true;
				}
				else if (currArg == "---debug") {
					enableDebugging = true;
				}
				else if (currArg == "---non-interactive") {
					interactive = false;
				}
				else if (currArg == "---nvidia-docker") {
					docker = NVIDIA_DOCKER;
				}
				else if (currArg == "---dry-run") {
					dryrun = true;
				}
				else if (currArg.substr(0,8) == "---name=") {
					name = currArg.substr(8);
				}
				else {
					trailingArgs += "\"" + currArg + "\" ";
				}
			}

			//Attempt to open the script file
			string scriptPath = argv[1];
			ifstream script(scriptPath.c_str());
			if (script.is_open() == false) {
				throw std::runtime_error("failed to open script file \"" + scriptPath + "\"");
			}

			//Attempt to read the second shebang line in the script file
			string shebang = "";
			std::getline(script, shebang);
			std::getline(script, shebang);
			if (script.fail()) {
				throw std::runtime_error("failed to read second shebang line from \"" + scriptPath + "\"");
			}

			//Verify that the shebang line is well-formed
			size_t spacePos = shebang.find(" ");
			if (shebang.substr(0,2) != "#!" || spacePos == string::npos) {
				throw std::runtime_error("invalid second shebang line in script file \"" + scriptPath + "\"");
			}

			//Parse the shebang line
			string dockerImage = shebang.substr(2, spacePos - 2);
			string interpreter = shebang.substr(spacePos + 1);

			//Determine the full path to the script file
			scriptPath = Utility::realPath(scriptPath);

			//Extract the directory and filename components of the script's path, as well as our current working directory
			string scriptFile = Utility::baseName(scriptPath);
			string scriptDir  = Utility::dirName(scriptPath);
			string workingDir = Utility::cwd();

			//Extract the docker image name, without trailing tag name
			string imageWithoutTag = dockerImage.substr(0, dockerImage.find(":"));

			//If the specified docker image (or the specific image and tag combination) requires
			//nvidia-docker, we invoke nvidia-docker instead of regular docker
			auto nvDockerImages = NvidiaDockerImages::getList();
			if (Utility::contains(nvDockerImages, imageWithoutTag) || Utility::contains(nvDockerImages, dockerImage)) {
				docker = NVIDIA_DOCKER;
			}

			//If we were invoked using the symlink `nvidia-docker-script`, always use `nvidia-docker`
			if (string(argv[0]) == "nvidia-docker-script") {
				docker = NVIDIA_DOCKER;
			}

			//Build the `docker run` command
			string command = docker + " run " +
				string("\"-v") + scriptDir + ":/scriptdir\" " +
				string("\"-v") + workingDir + ":/workingdir\" " +
				string((enableDebugging == true) ? "--privileged=true " : "") +
				string("--workdir=/workingdir ") +
				string("-e \"HOST_CWD=") + workingDir + "\" " +
				string((interactive == true) ? "-ti " : "-t ") +
				string((!name.empty()) ? "--name \"" + name + "\" " : "") +
				string("--rm --entrypoint=\"\" ") +
				string("\"") + dockerImage + "\" " +
				string("\"") + interpreter + "\" " +
				string("\"/scriptdir/") + scriptFile + "\" " + trailingArgs;

			//If verbose output was requested, display diagnostic information
			if (verboseOutput == true)
			{
				clog << "Docker image:       " << dockerImage << endl;
				clog << "Interpreter:        " << interpreter << endl;
				clog << "Script path:        " << scriptPath << endl;
				clog << "Script basename:    " << scriptFile << endl;
				clog << "Script dirname:     " << scriptDir << endl;
				clog << "Working directory:  " << workingDir << endl;
				clog << "Trailing arguments: " << trailingArgs << endl;
				clog << endl << "Docker command:" << endl << command << endl << endl;
			}

			//If we are performing a dry run, simply print the command that would have been invoked
			if (dryrun == true) {
				std::cout << command << std::endl;
			}
			else
			{
				//Invoke docker
				return system(command.c_str());
			}
		}
		catch (std::runtime_error& e)
		{
			clog << "Error: " << e.what() << endl << endl;
			return 1;
		}
	}
	else
	{
		clog << "Usage:" << endl << argv[0] << " <SCRIPT> [options] [args for script]" << endl << endl;
		clog << "The first line of the script file should be a normal Unix shebang line." << endl;
		clog << "The second line of the script file should be:" << endl;
		clog << "#!<IMAGE> <INTERPRETER>" << endl << endl;
		clog << "Supported options:" << endl;
		clog << "---verbose            Enable verbose output" << endl;
		clog << "---debug              Enable debugging inside the container" << endl;
		clog << "---non-interactive    Non-interactive mode" << endl;
		clog << "---nvidia-docker      Use `nvidia-docker` instead of `docker`" << endl;
		clog << "---dry-run            Output generated command instead of running it" << endl;
		clog << "---name=NAME          Specify container name" << endl;
		clog << endl;
	}

	return 0;
}
<|endoftext|>


<commit_before>#include "customtextedit.h"
#include <QMimeData>
#include <QDebug>

CustomTextEdit::CustomTextEdit()
{
    connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
    giFlag = 1;
}

void CustomTextEdit::dragEnterEvent(QDragEnterEvent *event)
{
    event->acceptProposedAction();
}

void CustomTextEdit::dropEvent(QDropEvent *event)
{
    emit this->customTextEdit_signal_processDropEvent(event);
}

void CustomTextEdit::dragMoveEvent(QDragMoveEvent *event)
{
    event->acceptProposedAction();
}

void CustomTextEdit::highlightCurrentLine()
{
    if(giFlag == 1){
        QList<QTextEdit::ExtraSelection> extraSelections = this->extraSelections();

        if(extraSelections.count() > 0){
            extraSelections.removeLast();
        }

        QTextEdit::ExtraSelection selection;

        QColor lineColor = QColor(this->palette().background().color().darker(130));

        selection.format.setBackground(lineColor);
        selection.format.setProperty(QTextFormat::FullWidthSelection, true);
        selection.cursor = textCursor();
        selection.cursor.clearSelection();
        extraSelections.append(selection);
        setExtraSelections(extraSelections);
    }
}

void CustomTextEdit::cte_slot_disableHighLight()
{
    giFlag = 0;
}

void CustomTextEdit::cte_slot_enableHighLight()
{
    giFlag = 1;
}
<commit_msg>Changed highligth line color<commit_after>#include "customtextedit.h"
#include <QMimeData>
#include <QDebug>

CustomTextEdit::CustomTextEdit()
{
    connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
    giFlag = 1;
}

void CustomTextEdit::dragEnterEvent(QDragEnterEvent *event)
{
    event->acceptProposedAction();
}

void CustomTextEdit::dropEvent(QDropEvent *event)
{
    emit this->customTextEdit_signal_processDropEvent(event);
}

void CustomTextEdit::dragMoveEvent(QDragMoveEvent *event)
{
    event->acceptProposedAction();
}

void CustomTextEdit::highlightCurrentLine()
{
    if(giFlag == 1){
        QList<QTextEdit::ExtraSelection> extraSelections = this->extraSelections();

        if(extraSelections.count() > 0){
            extraSelections.removeLast();
        }

        QTextEdit::ExtraSelection selection;

        QColor lineColor = QColor(this->palette().background().color().darker(110));

        selection.format.setBackground(lineColor);
        selection.format.setProperty(QTextFormat::FullWidthSelection, true);
        selection.cursor = textCursor();
        selection.cursor.clearSelection();
        extraSelections.append(selection);
        setExtraSelections(extraSelections);
    }
}

void CustomTextEdit::cte_slot_disableHighLight()
{
    giFlag = 0;
}

void CustomTextEdit::cte_slot_enableHighLight()
{
    giFlag = 1;
}
<|endoftext|>


<commit_before>// This Source Code Form is licensed MPLv2: http://mozilla.org/MPL/2.0
#include "cxxaux.hh"
#include "rapicornconfig.h"
#include "configbits.cc"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <zlib.h>
#include <vector>
#include <string>
using namespace Rapicorn;

/* rapicorn-zintern - small C source compression utility
 * Implemented without linking against librapicorn, as it may be used during the rapicorn build process.
 */

typedef std::string String;

static void zintern_error  (const char *format, ...) RAPICORN_PRINTF (1, 2);

static void
zintern_error (const char *format, ...)
{
  char buffer[4096];
  va_list args;
  va_start (args, format);
  vsnprintf (buffer, sizeof (buffer), format, args);
  va_end (args);
  buffer[sizeof (buffer) - 1] = 0;
  fprintf (stderr, "\nERROR: %s\n", buffer);
  _exit (1);
}

static bool use_compression = false;
static bool use_base_name = false;
static bool break_at_newlines = false;
static bool as_resource = false;

typedef struct {
  uint pos;
  bool pad;
} Config;
static Config config_init = { 0, 0 };

static inline void
print_uchar (Config *config,
	     uint8 d)
{
  if (config->pos > 70)
    {
      printf ("\"\n  \"");
      config->pos = 3;
      config->pad = false;
    }
  if (d == '\\')
    {
      printf ("\\\\");
      config->pos += 2;
    }
  else if (d == '\n')
    {
      printf ("\\n");
      config->pos += 2;
      if (break_at_newlines && config->pos > 3)
        config->pos |= 1 << 31;
    }
  else if (d == '"')
    {
      printf ("\\\"");
      config->pos += 2;
    }
  else if (d < 32 || d > 126 || d == '?')
    {
      printf ("\\%o", d);
      config->pos += 1 + 1 + (d > 7) + (d > 63);
      config->pad = d < 64;
      return;
    }
  else if (config->pad && d >= '0' && d <= '9')
    {
      printf ("\"\"");
      printf ("%c", d);
      config->pos += 3;
    }
  else
    {
      printf ("%c", d);
      config->pos += 1;
    }
  config->pad = false;
}

#define to_upper(c)     ((c) >='a' && (c) <='z' ? (c) - 'a' + 'A' : (c))
#define is_alnum(c)     (((c) >='A' && (c) <='Z') || ((c) >='a' && (c) <='z') || ((c) >='0' && (c) <='9'))
static String
to_cupper (const String &str)
{
  String s (str);
  for (uint i = 0; i < s.size(); i++)
    if (is_alnum (s[i]))
      s[i] = to_upper (s[i]);
    else
      s[i] = '_';
  return s;
}

static String
canonify (const String &string, const String &valid_chars, const String &substitute)
{
  const size_t l = string.size();
  const char *p = string.c_str();
  String d;
  for (size_t i = 0; i < l; i++)
    if (strchr (valid_chars.c_str(), p[i]))
      d += p[i];
    else
      d += substitute;
  return d;
}

static String
base_name (const String &fname)
{
  const char *name = fname.c_str();
  const char *b = strrchr (name, RAPICORN_DIR_SEPARATOR);
  return b ? b + 1 : name;
}

static void
gen_zfile (const char *name,
	   const char *file)
{
  std::vector<uint8> vdata;
  uint i, dlen = 0, mlen = 0;
  uLongf clen;
  String fname = use_base_name ? base_name (file) : file;
  Config config;
  FILE *f = fopen (file, "r");
  if (!f)
    zintern_error ("failed to open \"%s\": %s", file, strerror (errno));
  do
    {
      if (mlen <= dlen + 1024)
	{
	  mlen += 8192;
          vdata.resize (mlen);
	}
      dlen += fread (&vdata[dlen], 1, mlen - dlen, f);
    }
  while (!ferror (f) && !feof (f));

  if (ferror (f))
    zintern_error ("failed to read from \"%s\": %s", file, strerror (errno));

  std::vector<uint8> cdata;
  if (use_compression || as_resource)
    {
      int result;
      const char *err;
      clen = dlen + dlen / 100 + 64;
      cdata.resize (clen);
      result = compress2 (&cdata[0], &clen, &vdata[0], dlen, Z_BEST_COMPRESSION);
      switch (result)
	{
	case Z_OK:
	  err = NULL;
	  break;
	case Z_MEM_ERROR:
	  err = "out of memory";
	  break;
	case Z_BUF_ERROR:
	  err = "insufficient buffer size";
	  break;
	default:
	  err = "unknown error";
	  break;
	}
      if (err)
	zintern_error ("while compressing \"%s\": %s", file, err);
    }
  else
    {
      clen = dlen;
      cdata = vdata;
    }

  printf ("/* rapicorn-zintern file dump of %s */\n", file);

  if (as_resource)
    {
      if (name[0] == '/')
        zintern_error ("invalid absolute resource path (must be relative): %s", name);
      /* two things to consider for using the compressed data:
       * 1) for the reader code, pack_size + 1 must be smaller than data_size to identify compressed data.
       * 2) using compressed data requires runtime unpacking overhead and extra dynamic memory allocation,
       *    so it should provide a *significant* benefit if it's used.
       */
      const bool compress_resource = clen <= 0.75 * dlen && clen + 1 < dlen;
      const size_t rlen = compress_resource ? clen : dlen;
      const uint8 *rdata = rlen == dlen ? &vdata[0] : &cdata[0];
      String ident = canonify (name, "0123456789abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ", "_");

      config = config_init;
      printf ("RAPICORN_STATIC_RESOURCE_DATA (%s) =\n  \"", ident.c_str());
      for (i = 0; i < rlen; i++)
        print_uchar (&config, rdata[i]);
      printf ("\"; // %zu + 1\n", rlen);

      config = config_init;
      printf ("RAPICORN_STATIC_RESOURCE_ENTRY (%s, \"", ident.c_str());
      for (i = 0; i < strlen (name); i++)
        print_uchar (&config, name[i]);
      printf ("\", %u);\n", dlen);
    }
  else
    {
      config = config_init;
      printf ("#define %s_NAME \"", to_cupper (name).c_str());
      for (i = 0; i < fname.size(); i++)
        print_uchar (&config, fname[i]);
      printf ("\"\n");

      printf ("#define %s_SIZE (%u)\n", to_cupper (name).c_str(), dlen);

      config = config_init;
      printf ("static const unsigned char %s_DATA[%lu + 1] =\n", to_cupper (name).c_str(), clen);
      printf ("( \"");
      for (i = 0; i < clen; i++)
        print_uchar (&config, cdata[i]);
      printf ("\");\n");
    }

  fclose (f);
}

static int
help (int exitcode)
{
  printf ("usage: rapicorn-zintern [-h] [-b] [-z] [[name file]...]\n");
  if (exitcode != 0)
    exit (exitcode);
  printf ("  -h, --help    Print usage information\n");
  printf ("  -v, --version Print version and file paths\n");
  printf ("  -b            Strip directories from file names\n");
  printf ("  -n            Break output lines after newlines raw data\n");
  printf ("  -r            Produce Rapicorn resource declarations\n");
  printf ("  -z            Compress data blocks with libz\n");
  printf ("Parse (name, file) pairs and generate C source\n");
  printf ("containing inlined data blocks of the files given.\n");
  exit (0);
}

int
main (int argc, char *argv[])
{
  std::vector<String> arg_strings;

  for (int i = 1; i < argc; i++)
    {
      if (strcmp ("-z", argv[i]) == 0)
	{
	  use_compression = true;
	}
      else if (strcmp ("-r", argv[i]) == 0)
	{
	  as_resource = true;
	}
      else if (strcmp ("-b", argv[i]) == 0)
	{
	  use_base_name = true;
	}
      else if (strcmp ("-n", argv[i]) == 0)
	{
	  break_at_newlines = true;
	}
      else if (strcmp ("-h", argv[i]) == 0 || strcmp ("--help", argv[i]) == 0)
	{
	  return help (0);
	}
      else if (strcmp ("-v", argv[i]) == 0 || strcmp ("--version", argv[i]) == 0)
	{
          printf ("rapidrun (Rapicorn utilities) %s (Build ID: %s)\n", RAPICORN_VERSION, RAPICORN_BUILDID);
          printf ("Copyright (C) 2007 Tim Janik.\n");
          printf ("This is free software and comes with ABSOLUTELY NO WARRANTY; see\n");
          printf ("the source for copying conditions. Sources, examples and contact\n");
          printf ("information are available at http://rapicorn.org/.\n");
          exit (0);
	}
      else
	arg_strings.push_back (argv[i]);
    }

  if (arg_strings.size() % 2)
    return help (1);

  for (size_t i = 0; i < arg_strings.size(); i += 2)
    {
      const char *name = arg_strings[i + 0].c_str();
      const char *file = arg_strings[i + 1].c_str();
      gen_zfile (name, file);
    }

  return 0;
}
<commit_msg>RCORE: rapicorn-zintern.cc: generate resource file names internally<commit_after>// This Source Code Form is licensed MPLv2: http://mozilla.org/MPL/2.0
#include "cxxaux.hh"
#include "rapicornconfig.h"
#include "configbits.cc"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <zlib.h>
#include <vector>
#include <string>
using namespace Rapicorn;

/* rapicorn-zintern - small C source compression utility
 * Implemented without linking against librapicorn, as it may be used during the rapicorn build process.
 */

typedef std::string String;

static void zintern_error  (const char *format, ...) RAPICORN_PRINTF (1, 2);

static void
zintern_error (const char *format, ...)
{
  char buffer[4096];
  va_list args;
  va_start (args, format);
  vsnprintf (buffer, sizeof (buffer), format, args);
  va_end (args);
  buffer[sizeof (buffer) - 1] = 0;
  fprintf (stderr, "\nERROR: %s\n", buffer);
  _exit (1);
}

static bool use_compression = false;
static bool use_base_name = false;
static bool break_at_newlines = false;
static bool as_resource = false;

typedef struct {
  uint pos;
  bool pad;
} Config;
static Config config_init = { 0, 0 };

static inline void
print_uchar (Config *config,
	     uint8 d)
{
  if (config->pos > 70)
    {
      printf ("\"\n  \"");
      config->pos = 3;
      config->pad = false;
    }
  if (d == '\\')
    {
      printf ("\\\\");
      config->pos += 2;
    }
  else if (d == '\n')
    {
      printf ("\\n");
      config->pos += 2;
      if (break_at_newlines && config->pos > 3)
        config->pos |= 1 << 31;
    }
  else if (d == '"')
    {
      printf ("\\\"");
      config->pos += 2;
    }
  else if (d < 32 || d > 126 || d == '?')
    {
      printf ("\\%o", d);
      config->pos += 1 + 1 + (d > 7) + (d > 63);
      config->pad = d < 64;
      return;
    }
  else if (config->pad && d >= '0' && d <= '9')
    {
      printf ("\"\"");
      printf ("%c", d);
      config->pos += 3;
    }
  else
    {
      printf ("%c", d);
      config->pos += 1;
    }
  config->pad = false;
}

#define to_upper(c)     ((c) >='a' && (c) <='z' ? (c) - 'a' + 'A' : (c))
#define is_alnum(c)     (((c) >='A' && (c) <='Z') || ((c) >='a' && (c) <='z') || ((c) >='0' && (c) <='9'))
static String
to_cupper (const String &str)
{
  String s (str);
  for (uint i = 0; i < s.size(); i++)
    if (is_alnum (s[i]))
      s[i] = to_upper (s[i]);
    else
      s[i] = '_';
  return s;
}

static String
base_name (const String &fname)
{
  const char *name = fname.c_str();
  const char *b = strrchr (name, RAPICORN_DIR_SEPARATOR);
  return b ? b + 1 : name;
}

static void
gen_zfile (const String &file)
{
  // create nice resource path
  String fname = use_base_name ? base_name (file) : file;
  // strip ^[/.]
  while (fname.size() && strchr ("/.", fname[0]))
    fname.erase (fname.begin());
  // create C identifier
  String ident = fname;
  // substitute [/.-] with _
  for (size_t i = 0; i < ident.size(); i++)
    if (strchr ("./-", ident[i]))
      ident[i] = '_';
  // check identifier chars
  for (size_t i = 0; i < ident.size(); i++)
    if ((ident[i] >= 'a' && ident[i] <= 'z') ||
        (ident[i] >= 'A' && ident[i] <= 'Z') ||
        (i && ident[i] >= '0' && ident[i] <= '9') ||
        ident[i] == '_')
      ; // fine
    else
      zintern_error ("file name contains non-symbol characters: %s", file.c_str());
  // file processing
  std::vector<uint8> vdata;
  uint i, dlen = 0, mlen = 0;
  uLongf clen;
  Config config;
  FILE *f = fopen (file.c_str(), "r");
  if (!f)
    zintern_error ("failed to open \"%s\": %s", file.c_str(), strerror (errno));
  do
    {
      if (mlen <= dlen + 1024)
	{
	  mlen += 8192;
          vdata.resize (mlen);
	}
      dlen += fread (&vdata[dlen], 1, mlen - dlen, f);
    }
  while (!ferror (f) && !feof (f));

  if (ferror (f))
    zintern_error ("failed to read from \"%s\": %s", file.c_str(), strerror (errno));

  std::vector<uint8> cdata;
  if (use_compression || as_resource)
    {
      int result;
      const char *err;
      clen = dlen + dlen / 100 + 64;
      cdata.resize (clen);
      result = compress2 (&cdata[0], &clen, &vdata[0], dlen, Z_BEST_COMPRESSION);
      switch (result)
	{
	case Z_OK:
	  err = NULL;
	  break;
	case Z_MEM_ERROR:
	  err = "out of memory";
	  break;
	case Z_BUF_ERROR:
	  err = "insufficient buffer size";
	  break;
	default:
	  err = "unknown error";
	  break;
	}
      if (err)
	zintern_error ("while compressing \"%s\": %s", file.c_str(), err);
    }
  else
    {
      clen = dlen;
      cdata = vdata;
    }

  printf ("/* rapicorn-zintern file dump of %s */\n", file.c_str());

  if (as_resource)
    {
      /* two things to consider for using the compressed data:
       * 1) for the reader code, pack_size + 1 must be smaller than data_size to identify compressed data.
       * 2) using compressed data requires runtime unpacking overhead and extra dynamic memory allocation,
       *    so it should provide a *significant* benefit if it's used.
       */
      const bool compress_resource = clen <= 0.75 * dlen && clen + 1 < dlen;
      const size_t rlen = compress_resource ? clen : dlen;
      const uint8 *rdata = rlen == dlen ? &vdata[0] : &cdata[0];

      config = config_init;
      printf ("RAPICORN_STATIC_RESOURCE_DATA (%s) =\n  \"", ident.c_str());
      for (i = 0; i < rlen; i++)
        print_uchar (&config, rdata[i]);
      printf ("\"; // %zu + 1\n", rlen);

      config = config_init;
      printf ("RAPICORN_STATIC_RESOURCE_ENTRY (%s, \"", ident.c_str());
      for (i = 0; i < fname.size(); i++)
        print_uchar (&config, fname[i]);
      printf ("\", %u);\n", dlen);
    }
  else
    {
      config = config_init;
      printf ("#define %s_NAME \"", to_cupper (ident).c_str());
      for (i = 0; i < fname.size(); i++)
        print_uchar (&config, fname[i]);
      printf ("\"\n");

      printf ("#define %s_SIZE (%u)\n", to_cupper (ident).c_str(), dlen);

      config = config_init;
      printf ("static const unsigned char %s_DATA[%lu + 1] =\n", to_cupper (ident).c_str(), clen);
      printf ("( \"");
      for (i = 0; i < clen; i++)
        print_uchar (&config, cdata[i]);
      printf ("\");\n");
    }

  fclose (f);
}

static int
help (int exitcode)
{
  printf ("usage: rapicorn-zintern [-h] [-b] [-z] [files...]\n");
  if (exitcode != 0)
    exit (exitcode);
  printf ("  -h, --help    Print usage information\n");
  printf ("  -v, --version Print version and file paths\n");
  printf ("  -b            Strip directories from file names\n");
  printf ("  -n            Break output lines after newlines raw data\n");
  printf ("  -r            Produce Rapicorn resource declarations\n");
  printf ("  -z            Compress data blocks with libz\n");
  printf ("Parse (name, file) pairs and generate C source\n");
  printf ("containing inlined data blocks of the files given.\n");
  exit (0);
}

int
main (int argc, char *argv[])
{
  std::vector<String> arg_strings;

  for (int i = 1; i < argc; i++)
    {
      if (strcmp ("-z", argv[i]) == 0)
	{
	  use_compression = true;
	}
      else if (strcmp ("-r", argv[i]) == 0)
	{
	  as_resource = true;
	}
      else if (strcmp ("-b", argv[i]) == 0)
	{
	  use_base_name = true;
	}
      else if (strcmp ("-n", argv[i]) == 0)
	{
	  break_at_newlines = true;
	}
      else if (strcmp ("-h", argv[i]) == 0 || strcmp ("--help", argv[i]) == 0)
	{
	  return help (0);
	}
      else if (strcmp ("-v", argv[i]) == 0 || strcmp ("--version", argv[i]) == 0)
	{
          printf ("rapidrun (Rapicorn utilities) %s (Build ID: %s)\n", RAPICORN_VERSION, RAPICORN_BUILDID);
          printf ("Copyright (C) 2007 Tim Janik.\n");
          printf ("This is free software and comes with ABSOLUTELY NO WARRANTY; see\n");
          printf ("the source for copying conditions. Sources, examples and contact\n");
          printf ("information are available at http://rapicorn.org/.\n");
          exit (0);
	}
      else
	arg_strings.push_back (argv[i]);
    }

  if (arg_strings.size() == 0)
    return help (1);

  for (size_t i = 0; i < arg_strings.size(); i++)
    {
      const String file = arg_strings[i + 0];
      gen_zfile (file);
    }

  return 0;
}
<|endoftext|>


<commit_before>#include "stdafx.h"

BDD representState(Cudd manager, std::vector<bool> values) {
    BDD bdd = manager.bddOne();
    int i = 0;
    for (auto it = std::begin(values); it != std::end(values); ++it) {
        BDD var = manager.bddVar(i);
        if (!*it) {
            var = !var;
        }
        bdd = var * bdd;
        i++;
    }
    return bdd;
}

BDD representCnf(Cudd manager, std::vector<int> cnf) {
    BDD bdd = manager.bddZero();
    for (auto it = std::begin(cnf); it != std::end(cnf); ++it) {
        BDD var = manager.bddVar(abs(*it));
        if (*it < 0) {
            var = !var;
        }
        bdd = var + bdd;
    }
    return bdd;
}

BDD representUpdateFunction(Cudd manager, std::vector<std::vector<int>> cnfs) {
    BDD bdd = manager.bddOne();
    for (auto it = std::begin(cnfs); it != std::end(cnfs); ++it) {
        bdd = bdd * representCnf(manager, *it);
    }
    return bdd;
}

BDD logicalEquivalence(BDD a, BDD b) {
    return (a * b) + ((!a) * (!b));
}

BDD representSyncTransitionRelation(Cudd manager, std::vector<std::vector<std::vector<int>>> network) {
    BDD bdd = manager.bddOne();
    int i = 0;
    for (auto it = std::begin(network); it != std::end(network); ++it) {
        BDD f = representUpdateFunction(manager, *it);
        BDD vPrime = manager.bddVar(network.size() + i);
        BDD transition = logicalEquivalence(vPrime, f);
        bdd = transition * bdd;
        i++;
    }
    return bdd;
}

BDD otherVarsDoNotChange(Cudd manager, int i, int numVars) {
    BDD bdd = manager.bddOne();
    for (int j = 0; j < numVars; j++) {
        if (j != i) {
            BDD v = manager.bddVar(j);
            BDD vPrime = manager.bddVar(numVars + j);
            bdd = bdd * logicalEquivalence(v, vPrime);
        }
    }
    return bdd;
}

BDD representAsyncTransitionRelation(Cudd manager, std::vector<std::vector<std::vector<int>>> network) {
    BDD fixpoint = manager.bddOne();
    for (int i = 0; i < network.size(); i++) {
        BDD v = manager.bddVar(i);
        BDD vPrime = manager.bddVar(network.size() + i);
        fixpoint = fixpoint * logicalEquivalence(v, vPrime);
    }

    BDD bdd = manager.bddZero();
    int i = 0;
    for (auto it = std::begin(network); it != std::end(network); ++it) {
        BDD v = manager.bddVar(i);
        BDD vPrime = manager.bddVar(network.size() + i);
        BDD vChanges = !logicalEquivalence(v, vPrime);
        BDD f = representUpdateFunction(manager, *it);
        BDD update = logicalEquivalence(vPrime, f) * otherVarsDoNotChange(manager, i, network.size());
        BDD transition = update * (fixpoint + vChanges);
        bdd = transition + bdd;
        i++;
    }

    return bdd;
}

BDD renameRemovingPrimes(BDD bdd, int numVars) {
    int *permute = new int[numVars * 2];
    for (int i = 0; i < numVars; i++) {
        permute[i] = i;
        permute[i + numVars] = i;
    }
    BDD r = bdd.Permute(permute);
    delete[] permute;
    return r;
}

BDD nonPrimeVariables(Cudd manager, int numVars) {
    return representState(manager, std::vector<bool>(numVars, true));
}

BDD primeVariables(Cudd manager, int numVars) {
    BDD bdd = manager.bddOne();
    for (int i = numVars; i < numVars * 2; i++) {
        BDD var = manager.bddVar(i);
        bdd = var * bdd;
    }
    return bdd;
}

BDD immediateSuccessorStates(Cudd manager, BDD transitionBdd, BDD valuesBdd, int numVars) {
    BDD bdd = transitionBdd * valuesBdd;
    bdd = bdd.ExistAbstract(nonPrimeVariables(manager, numVars));
    bdd = renameRemovingPrimes(bdd, numVars);
    return bdd;
}

BDD forwardReachableStates(Cudd manager, BDD transitionBdd, BDD valuesBdd, int numVars) {
    BDD reachable = manager.bddZero();
    BDD frontier = valuesBdd;

    while (frontier != manager.bddZero()) {
        frontier = immediateSuccessorStates(manager, transitionBdd, frontier, numVars) * !reachable;
        reachable = reachable + frontier;
    }
    return reachable;
}

BDD renameAddingPrimes(BDD bdd, int numVars) {
    int *permute = new int[numVars * 2];
    for (int i = 0; i < numVars; i++) {
        permute[i] = i + numVars;
        permute[i + numVars] = i + numVars;
    }

    BDD r = bdd.Permute(permute);
    delete[] permute;
    return r;
}

BDD immediatePredecessorStates(Cudd manager, BDD transitionBdd, BDD valuesBdd, int numVars) {
    valuesBdd = renameAddingPrimes(valuesBdd, numVars);
    BDD bdd = transitionBdd * valuesBdd;
    bdd = bdd.ExistAbstract(primeVariables(manager, numVars));
    return bdd;
}

BDD backwardReachableStates(Cudd manager, BDD transitionBdd, BDD valuesBdd, int numVars) {
    BDD reachable = manager.bddZero();
    BDD frontier = valuesBdd;

    while (frontier != manager.bddZero()) {
        frontier = immediatePredecessorStates(manager, transitionBdd, frontier, numVars) * !reachable;
        reachable = reachable + frontier;
    }
    return reachable;
}

BDD randomState(Cudd manager, BDD S, int numVars) {
    char *out = new char[numVars * 2];
    S.PickOneCube(out);

    std::vector<bool> values;
    for (int i = 0; i < numVars; i++) {
        if (out[i] == 0) {
            values.push_back(false);
        }
        else {
            values.push_back(true);
        }
    }

    delete[] out;
    return representState(manager, values);
}

std::vector<BDD> attractors(Cudd manager, BDD transitionBdd, int numVars) {
    std::vector<BDD> attractors = std::vector<BDD>();
    BDD S = manager.bddOne();
    while (S != manager.bddZero()) {
        BDD s = randomState(manager, S, numVars);
        BDD fr = forwardReachableStates(manager, transitionBdd, s, numVars);
        BDD br = backwardReachableStates(manager, transitionBdd, s, numVars);

        if ((fr * !br) == manager.bddZero()) {
            attractors.push_back(fr);
        }

        S = S * !(s + br);
    }
    return attractors;
}

int main() {
    //Cebpa, Pu.1, Gata2, Gata1, Fog1, EKLF, Fli1, Scl, cJun, EgrNab, Gfi1
    std::vector<bool> cmpInitial { true, true, true, false, false, false, false, false, false, false, false };
    std::vector<std::vector<int>> cebpa { { 0 },{ -7 },{ -3, -4 } };
    std::vector<std::vector<int>> pu1 { { 0, 1 },{ -2 },{ -3 } };
    std::vector<std::vector<int>> gata2 { { 3 },{ -1 },{ -3, -4 } };
    std::vector<std::vector<int>> gata1 { { 2, 3, 6 },{ -1 } };
    std::vector<std::vector<int>> fog1 { { 3 } };
    std::vector<std::vector<int>> eklf { { 3 },{ -6 } };
    std::vector<std::vector<int>> fli1 { { 3 },{ -5 } };
    std::vector<std::vector<int>> scl { { 3 },{ -1 } };
    std::vector<std::vector<int>> cJun { { 1 },{ -10 } };
    std::vector<std::vector<int>> egrNab { { 1 },{ 8 },{ -10 } };
    std::vector<std::vector<int>> gfi1 { { 0 },{ -9 } };
    std::vector<std::vector<std::vector<int>>> cmp { cebpa, pu1, gata2, gata1, fog1, eklf, fli1, scl, cJun, egrNab, gfi1 };

    Cudd manager(0, 0);
    BDD initialStateBdd = representState(manager, cmpInitial);

    BDD transitionBddA = representAsyncTransitionRelation(manager, cmp);
    BDD statespace = forwardReachableStates(manager, transitionBddA, initialStateBdd, cmpInitial.size());
    std::cout << statespace.CountMinterm(cmpInitial.size());
    std::cout << "\n";

    std::vector<BDD> attsA = attractors(manager, transitionBddA, cmpInitial.size());
    for (BDD attractor : attsA) {
        attractor.PrintMinterm();
        std::cout << "\n";
    }

    std::cout << "--------------------------------\n";

    BDD transitionBddS = representSyncTransitionRelation(manager, cmp);
    std::vector<BDD> attsS = attractors(manager, transitionBddS, cmpInitial.size());
    for (BDD attractor : attsS) {
        attractor.PrintMinterm();
        std::cout << "\n";
    }

    return 0;
}
<commit_msg>Pass by const reference<commit_after>#include "stdafx.h"

BDD representState(const Cudd& manager, const std::vector<bool>& values) {
    BDD bdd = manager.bddOne();
    int i = 0;
    for (auto it = std::begin(values); it != std::end(values); ++it) {
        BDD var = manager.bddVar(i);
        if (!*it) {
            var = !var;
        }
        bdd = var * bdd;
        i++;
    }
    return bdd;
}

BDD representCnf(const Cudd& manager, const std::vector<int>& cnf) {
    BDD bdd = manager.bddZero();
    for (auto it = std::begin(cnf); it != std::end(cnf); ++it) {
        BDD var = manager.bddVar(abs(*it));
        if (*it < 0) {
            var = !var;
        }
        bdd = var + bdd;
    }
    return bdd;
}

BDD representUpdateFunction(const Cudd& manager, const std::vector<std::vector<int>>& cnfs) {
    BDD bdd = manager.bddOne();
    for (auto it = std::begin(cnfs); it != std::end(cnfs); ++it) {
        bdd = bdd * representCnf(manager, *it);
    }
    return bdd;
}

BDD implication(const BDD& a, const BDD& b) {
    return (!a) + b;
}

BDD logicalEquivalence(const BDD& a, const BDD& b) {
    return (a * b) + ((!a) * (!b));
}

BDD representSyncTransitionRelation(const Cudd& manager, const std::vector<std::vector<std::vector<int>>>& network) {
    BDD bdd = manager.bddOne();
    int i = 0;
    for (auto it = std::begin(network); it != std::end(network); ++it) {
        BDD f = representUpdateFunction(manager, *it);
        BDD vPrime = manager.bddVar(network.size() + i);
        BDD transition = logicalEquivalence(vPrime, f);
        bdd = transition * bdd;
        i++;
    }
    return bdd;
}

BDD otherVarsDoNotChange(const Cudd& manager, int i, int numVars) {
    BDD bdd = manager.bddOne();
    for (int j = 0; j < numVars; j++) {
        if (j != i) {
            BDD v = manager.bddVar(j);
            BDD vPrime = manager.bddVar(numVars + j);
            bdd = bdd * logicalEquivalence(v, vPrime);
        }
    }
    return bdd;
}

BDD representAsyncTransitionRelation(const Cudd& manager, const std::vector<std::vector<std::vector<int>>>& network) {
    BDD fixpoint = manager.bddOne();
    for (int i = 0; i < network.size(); i++) {
        BDD v = manager.bddVar(i);
        BDD vPrime = manager.bddVar(network.size() + i);
        fixpoint = fixpoint * logicalEquivalence(v, vPrime);
    }

    BDD bdd = manager.bddZero();
    int i = 0;
    for (auto it = std::begin(network); it != std::end(network); ++it) {
        BDD v = manager.bddVar(i);
        BDD vPrime = manager.bddVar(network.size() + i);
        BDD vChanges = !logicalEquivalence(v, vPrime);
        BDD f = representUpdateFunction(manager, *it);
        BDD update = logicalEquivalence(vPrime, f) * otherVarsDoNotChange(manager, i, network.size());
        BDD transition = update * (fixpoint + vChanges);
        bdd = transition + bdd;
        i++;
    }

    return bdd;
}

BDD renameRemovingPrimes(const BDD& bdd, int numVars) {
    int *permute = new int[numVars * 2];
    for (int i = 0; i < numVars; i++) {
        permute[i] = i;
        permute[i + numVars] = i;
    }
    BDD r = bdd.Permute(permute);
    delete[] permute;
    return r;
}

BDD nonPrimeVariables(const Cudd& manager, int numVars) {
    return representState(manager, std::vector<bool>(numVars, true));
}

BDD primeVariables(const Cudd& manager, int numVars) {
    BDD bdd = manager.bddOne();
    for (int i = numVars; i < numVars * 2; i++) {
        BDD var = manager.bddVar(i);
        bdd = var * bdd;
    }
    return bdd;
}

BDD immediateSuccessorStates(const Cudd& manager, const BDD& transitionBdd, const BDD& valuesBdd, int numVars) {
    BDD bdd = transitionBdd * valuesBdd;
    bdd = bdd.ExistAbstract(nonPrimeVariables(manager, numVars));
    bdd = renameRemovingPrimes(bdd, numVars);
    return bdd;
}

BDD forwardReachableStates(const Cudd& manager, const BDD& transitionBdd, const BDD& valuesBdd, int numVars) {
    BDD reachable = manager.bddZero();
    BDD frontier = valuesBdd;

    while (frontier != manager.bddZero()) {
        frontier = immediateSuccessorStates(manager, transitionBdd, frontier, numVars) * !reachable;
        reachable = reachable + frontier;
    }
    return reachable;
}

BDD renameAddingPrimes(const BDD& bdd, int numVars) {
    int *permute = new int[numVars * 2];
    for (int i = 0; i < numVars; i++) {
        permute[i] = i + numVars;
        permute[i + numVars] = i + numVars;
    }

    BDD r = bdd.Permute(permute);
    delete[] permute;
    return r;
}

BDD immediatePredecessorStates(const Cudd& manager, const BDD& transitionBdd, const BDD& valuesBdd, int numVars) {
    BDD bdd = renameAddingPrimes(valuesBdd, numVars);
    bdd = transitionBdd * valuesBdd;
    bdd = bdd.ExistAbstract(primeVariables(manager, numVars));
    return bdd;
}

BDD backwardReachableStates(const Cudd& manager, const BDD& transitionBdd, const BDD& valuesBdd, int numVars) {
    BDD reachable = manager.bddZero();
    BDD frontier = valuesBdd;

    while (frontier != manager.bddZero()) {
        frontier = immediatePredecessorStates(manager, transitionBdd, frontier, numVars) * !reachable;
        reachable = reachable + frontier;
    }
    return reachable;
}

BDD randomState(const Cudd& manager, const BDD& S, int numVars) {
    char *out = new char[numVars * 2];
    S.PickOneCube(out);

    std::vector<bool> values;
    for (int i = 0; i < numVars; i++) {
        if (out[i] == 0) { // careful with = vs == in c++
            values.push_back(false);
        }
        else {
            values.push_back(true); // ideally, on 2 you would choose randomly between 0 and 1. may not matter
        }
    }

    delete[] out;
    return representState(manager, values);
}

std::vector<BDD> attractors(const Cudd&  manager, const BDD& transitionBdd, int numVars) {
    std::vector<BDD> attractors = std::vector<BDD>();
    BDD S = manager.bddOne();
    while (S != manager.bddZero()) {
        BDD s = randomState(manager, S, numVars);
        BDD fr = forwardReachableStates(manager, transitionBdd, s, numVars);
        BDD br = backwardReachableStates(manager, transitionBdd, s, numVars);

        if ((fr * !br) == manager.bddZero()) {
            attractors.push_back(fr);
        }

        S = S * !(s + br);
    }
    return attractors;
}

int main() {
    //Cebpa, Pu.1, Gata2, Gata1, Fog1, EKLF, Fli1, Scl, cJun, EgrNab, Gfi1
    std::vector<bool> cmpInitial{ true, true, true, false, false, false, false, false, false, false, false };
    std::vector<std::vector<int>> cebpa{ { 0 },{ -7 },{ -3, -4 } };
    std::vector<std::vector<int>> pu1{ { 0, 1 },{ -2 },{ -3 } };
    std::vector<std::vector<int>> gata2{ { 3 },{ -1 },{ -3, -4 } };
    std::vector<std::vector<int>> gata1{ { 2, 3, 6 },{ -1 } };
    std::vector<std::vector<int>> fog1{ { 3 } };
    std::vector<std::vector<int>> eklf{ { 3 },{ -6 } };
    std::vector<std::vector<int>> fli1{ { 3 },{ -5 } };
    std::vector<std::vector<int>> scl{ { 3 },{ -1 } };
    std::vector<std::vector<int>> cJun{ { 1 },{ -10 } };
    std::vector<std::vector<int>> egrNab{ { 1 },{ 8 },{ -10 } };
    std::vector<std::vector<int>> gfi1{ { 0 },{ -9 } };
    std::vector<std::vector<std::vector<int>>> cmp{ cebpa, pu1, gata2, gata1, fog1, eklf, fli1, scl, cJun, egrNab, gfi1 };

    Cudd manager(0, 0);
    BDD initialStateBdd = representState(manager, cmpInitial);

    BDD transitionBddA = representAsyncTransitionRelation(manager, cmp);
    BDD statespace = forwardReachableStates(manager, transitionBddA, initialStateBdd, cmpInitial.size());
    std::cout << statespace.CountMinterm(cmpInitial.size());
    std::cout << "\n";

    std::vector<BDD> attsA = attractors(manager, transitionBddA, cmpInitial.size());
    for (BDD attractor : attsA) {
        attractor.PrintMinterm();
        std::cout << "\n";
    }

    std::cout << "--------------------------------\n";

    BDD transitionBddS = representSyncTransitionRelation(manager, cmp);
    std::vector<BDD> attsS = attractors(manager, transitionBddS, cmpInitial.size());
    for (BDD attractor : attsS) {
        attractor.PrintMinterm();
        std::cout << "\n";
    }

    return 0;
}<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/test/fake_encoder.h"

#include "testing/gtest/include/gtest/gtest.h"

#include "webrtc/modules/video_coding/codecs/interface/video_codec_interface.h"
#include "webrtc/system_wrappers/interface/sleep.h"

namespace webrtc {
namespace test {

FakeEncoder::FakeEncoder(Clock* clock)
    : clock_(clock),
      callback_(NULL),
      target_bitrate_kbps_(0),
      max_target_bitrate_kbps_(-1),
      last_encode_time_ms_(0) {
  // Generate some arbitrary not-all-zero data
  for (size_t i = 0; i < sizeof(encoded_buffer_); ++i) {
    encoded_buffer_[i] = static_cast<uint8_t>(i);
  }
}

FakeEncoder::~FakeEncoder() {}

void FakeEncoder::SetMaxBitrate(int max_kbps) {
  assert(max_kbps >= -1);  // max_kbps == -1 disables it.
  max_target_bitrate_kbps_ = max_kbps;
}

int32_t FakeEncoder::InitEncode(const VideoCodec* config,
                                int32_t number_of_cores,
                                size_t max_payload_size) {
  config_ = *config;
  target_bitrate_kbps_ = config_.startBitrate;
  return 0;
}

int32_t FakeEncoder::Encode(
    const I420VideoFrame& input_image,
    const CodecSpecificInfo* codec_specific_info,
    const std::vector<VideoFrameType>* frame_types) {
  assert(config_.maxFramerate > 0);
  int64_t time_since_last_encode_ms = 1000 / config_.maxFramerate;
  int64_t time_now_ms = clock_->TimeInMilliseconds();
  const bool first_encode = last_encode_time_ms_ == 0;
  if (!first_encode) {
    // For all frames but the first we can estimate the display time by looking
    // at the display time of the previous frame.
    time_since_last_encode_ms = time_now_ms - last_encode_time_ms_;
  }

  size_t bits_available =
      static_cast<size_t>(target_bitrate_kbps_ * time_since_last_encode_ms);
  size_t min_bits = static_cast<size_t>(
      config_.simulcastStream[0].minBitrate * time_since_last_encode_ms);
  if (bits_available < min_bits)
    bits_available = min_bits;
  size_t max_bits =
      static_cast<size_t>(max_target_bitrate_kbps_ * time_since_last_encode_ms);
  if (max_bits > 0 && max_bits < bits_available)
    bits_available = max_bits;
  last_encode_time_ms_ = time_now_ms;

  assert(config_.numberOfSimulcastStreams > 0);
  for (unsigned char i = 0; i < config_.numberOfSimulcastStreams; ++i) {
    CodecSpecificInfo specifics;
    memset(&specifics, 0, sizeof(specifics));
    specifics.codecType = kVideoCodecGeneric;
    specifics.codecSpecific.generic.simulcast_idx = i;
    size_t min_stream_bits = static_cast<size_t>(
        config_.simulcastStream[i].minBitrate * time_since_last_encode_ms);
    size_t max_stream_bits = static_cast<size_t>(
        config_.simulcastStream[i].maxBitrate * time_since_last_encode_ms);
    size_t stream_bits = (bits_available > max_stream_bits) ? max_stream_bits :
        bits_available;
    size_t stream_bytes = (stream_bits + 7) / 8;
    if (first_encode) {
      // The first frame is a key frame and should be larger.
      // TODO(holmer): The FakeEncoder should store the bits_available between
      // encodes so that it can compensate for oversized frames.
      stream_bytes *= 10;
    }
    if (stream_bytes > sizeof(encoded_buffer_))
      stream_bytes = sizeof(encoded_buffer_);

    EncodedImage encoded(
        encoded_buffer_, stream_bytes, sizeof(encoded_buffer_));
    encoded._timeStamp = input_image.timestamp();
    encoded.capture_time_ms_ = input_image.render_time_ms();
    encoded._frameType = (*frame_types)[i];
    // Always encode something on the first frame.
    if (min_stream_bits > bits_available && i > 0) {
      encoded._length = 0;
      encoded._frameType = kSkipFrame;
    }
    assert(callback_ != NULL);
    if (callback_->Encoded(encoded, &specifics, NULL) != 0)
      return -1;
    bits_available -= std::min(encoded._length * 8, bits_available);
  }
  return 0;
}

int32_t FakeEncoder::RegisterEncodeCompleteCallback(
    EncodedImageCallback* callback) {
  callback_ = callback;
  return 0;
}

int32_t FakeEncoder::Release() { return 0; }

int32_t FakeEncoder::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
  return 0;
}

int32_t FakeEncoder::SetRates(uint32_t new_target_bitrate, uint32_t framerate) {
  target_bitrate_kbps_ = new_target_bitrate;
  return 0;
}

FakeH264Encoder::FakeH264Encoder(Clock* clock)
    : FakeEncoder(clock), callback_(NULL), idr_counter_(0) {
  FakeEncoder::RegisterEncodeCompleteCallback(this);
}

int32_t FakeH264Encoder::RegisterEncodeCompleteCallback(
    EncodedImageCallback* callback) {
  callback_ = callback;
  return 0;
}

int32_t FakeH264Encoder::Encoded(const EncodedImage& encoded_image,
                                 const CodecSpecificInfo* codec_specific_info,
                                 const RTPFragmentationHeader* fragments) {
  const size_t kSpsSize = 8;
  const size_t kPpsSize = 11;
  const int kIdrFrequency = 10;
  RTPFragmentationHeader fragmentation;
  if (idr_counter_++ % kIdrFrequency == 0 &&
      encoded_image._length > kSpsSize + kPpsSize + 1) {
    const size_t kNumSlices = 3;
    fragmentation.VerifyAndAllocateFragmentationHeader(kNumSlices);
    fragmentation.fragmentationOffset[0] = 0;
    fragmentation.fragmentationLength[0] = kSpsSize;
    fragmentation.fragmentationOffset[1] = kSpsSize;
    fragmentation.fragmentationLength[1] = kPpsSize;
    fragmentation.fragmentationOffset[2] = kSpsSize + kPpsSize;
    fragmentation.fragmentationLength[2] =
        encoded_image._length - (kSpsSize + kPpsSize);
    const size_t kSpsNalHeader = 0x37;
    const size_t kPpsNalHeader = 0x38;
    const size_t kIdrNalHeader = 0x15;
    encoded_image._buffer[fragmentation.fragmentationOffset[0]] = kSpsNalHeader;
    encoded_image._buffer[fragmentation.fragmentationOffset[1]] = kPpsNalHeader;
    encoded_image._buffer[fragmentation.fragmentationOffset[2]] = kIdrNalHeader;
  } else {
    const size_t kNumSlices = 1;
    fragmentation.VerifyAndAllocateFragmentationHeader(kNumSlices);
    fragmentation.fragmentationOffset[0] = 0;
    fragmentation.fragmentationLength[0] = encoded_image._length;
    const size_t kNalHeader = 0x11;
    encoded_image._buffer[fragmentation.fragmentationOffset[0]] = kNalHeader;
  }
  uint8_t value = 0;
  int fragment_counter = 0;
  for (size_t i = 0; i < encoded_image._length; ++i) {
    if (fragment_counter == fragmentation.fragmentationVectorSize ||
        i != fragmentation.fragmentationOffset[fragment_counter]) {
      encoded_image._buffer[i] = value++;
    } else {
      ++fragment_counter;
    }
  }
  return callback_->Encoded(encoded_image, NULL, &fragmentation);
}

DelayedEncoder::DelayedEncoder(Clock* clock, int delay_ms)
    : test::FakeEncoder(clock),
      delay_ms_(delay_ms) {}

int32_t DelayedEncoder::Encode(const I420VideoFrame& input_image,
                               const CodecSpecificInfo* codec_specific_info,
                               const std::vector<VideoFrameType>* frame_types) {
  SleepMs(delay_ms_);
  return FakeEncoder::Encode(input_image, codec_specific_info, frame_types);
}
}  // namespace test
}  // namespace webrtc
<commit_msg>Fix the value of the first byte of nal unit generated by fake H.264 encoder.<commit_after>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/test/fake_encoder.h"

#include "testing/gtest/include/gtest/gtest.h"

#include "webrtc/modules/video_coding/codecs/interface/video_codec_interface.h"
#include "webrtc/system_wrappers/interface/sleep.h"

namespace webrtc {
namespace test {

FakeEncoder::FakeEncoder(Clock* clock)
    : clock_(clock),
      callback_(NULL),
      target_bitrate_kbps_(0),
      max_target_bitrate_kbps_(-1),
      last_encode_time_ms_(0) {
  // Generate some arbitrary not-all-zero data
  for (size_t i = 0; i < sizeof(encoded_buffer_); ++i) {
    encoded_buffer_[i] = static_cast<uint8_t>(i);
  }
}

FakeEncoder::~FakeEncoder() {}

void FakeEncoder::SetMaxBitrate(int max_kbps) {
  assert(max_kbps >= -1);  // max_kbps == -1 disables it.
  max_target_bitrate_kbps_ = max_kbps;
}

int32_t FakeEncoder::InitEncode(const VideoCodec* config,
                                int32_t number_of_cores,
                                size_t max_payload_size) {
  config_ = *config;
  target_bitrate_kbps_ = config_.startBitrate;
  return 0;
}

int32_t FakeEncoder::Encode(
    const I420VideoFrame& input_image,
    const CodecSpecificInfo* codec_specific_info,
    const std::vector<VideoFrameType>* frame_types) {
  assert(config_.maxFramerate > 0);
  int64_t time_since_last_encode_ms = 1000 / config_.maxFramerate;
  int64_t time_now_ms = clock_->TimeInMilliseconds();
  const bool first_encode = last_encode_time_ms_ == 0;
  if (!first_encode) {
    // For all frames but the first we can estimate the display time by looking
    // at the display time of the previous frame.
    time_since_last_encode_ms = time_now_ms - last_encode_time_ms_;
  }

  size_t bits_available =
      static_cast<size_t>(target_bitrate_kbps_ * time_since_last_encode_ms);
  size_t min_bits = static_cast<size_t>(
      config_.simulcastStream[0].minBitrate * time_since_last_encode_ms);
  if (bits_available < min_bits)
    bits_available = min_bits;
  size_t max_bits =
      static_cast<size_t>(max_target_bitrate_kbps_ * time_since_last_encode_ms);
  if (max_bits > 0 && max_bits < bits_available)
    bits_available = max_bits;
  last_encode_time_ms_ = time_now_ms;

  assert(config_.numberOfSimulcastStreams > 0);
  for (unsigned char i = 0; i < config_.numberOfSimulcastStreams; ++i) {
    CodecSpecificInfo specifics;
    memset(&specifics, 0, sizeof(specifics));
    specifics.codecType = kVideoCodecGeneric;
    specifics.codecSpecific.generic.simulcast_idx = i;
    size_t min_stream_bits = static_cast<size_t>(
        config_.simulcastStream[i].minBitrate * time_since_last_encode_ms);
    size_t max_stream_bits = static_cast<size_t>(
        config_.simulcastStream[i].maxBitrate * time_since_last_encode_ms);
    size_t stream_bits = (bits_available > max_stream_bits) ? max_stream_bits :
        bits_available;
    size_t stream_bytes = (stream_bits + 7) / 8;
    if (first_encode) {
      // The first frame is a key frame and should be larger.
      // TODO(holmer): The FakeEncoder should store the bits_available between
      // encodes so that it can compensate for oversized frames.
      stream_bytes *= 10;
    }
    if (stream_bytes > sizeof(encoded_buffer_))
      stream_bytes = sizeof(encoded_buffer_);

    EncodedImage encoded(
        encoded_buffer_, stream_bytes, sizeof(encoded_buffer_));
    encoded._timeStamp = input_image.timestamp();
    encoded.capture_time_ms_ = input_image.render_time_ms();
    encoded._frameType = (*frame_types)[i];
    // Always encode something on the first frame.
    if (min_stream_bits > bits_available && i > 0) {
      encoded._length = 0;
      encoded._frameType = kSkipFrame;
    }
    assert(callback_ != NULL);
    if (callback_->Encoded(encoded, &specifics, NULL) != 0)
      return -1;
    bits_available -= std::min(encoded._length * 8, bits_available);
  }
  return 0;
}

int32_t FakeEncoder::RegisterEncodeCompleteCallback(
    EncodedImageCallback* callback) {
  callback_ = callback;
  return 0;
}

int32_t FakeEncoder::Release() { return 0; }

int32_t FakeEncoder::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
  return 0;
}

int32_t FakeEncoder::SetRates(uint32_t new_target_bitrate, uint32_t framerate) {
  target_bitrate_kbps_ = new_target_bitrate;
  return 0;
}

FakeH264Encoder::FakeH264Encoder(Clock* clock)
    : FakeEncoder(clock), callback_(NULL), idr_counter_(0) {
  FakeEncoder::RegisterEncodeCompleteCallback(this);
}

int32_t FakeH264Encoder::RegisterEncodeCompleteCallback(
    EncodedImageCallback* callback) {
  callback_ = callback;
  return 0;
}

int32_t FakeH264Encoder::Encoded(const EncodedImage& encoded_image,
                                 const CodecSpecificInfo* codec_specific_info,
                                 const RTPFragmentationHeader* fragments) {
  const size_t kSpsSize = 8;
  const size_t kPpsSize = 11;
  const int kIdrFrequency = 10;
  RTPFragmentationHeader fragmentation;
  if (idr_counter_++ % kIdrFrequency == 0 &&
      encoded_image._length > kSpsSize + kPpsSize + 1) {
    const size_t kNumSlices = 3;
    fragmentation.VerifyAndAllocateFragmentationHeader(kNumSlices);
    fragmentation.fragmentationOffset[0] = 0;
    fragmentation.fragmentationLength[0] = kSpsSize;
    fragmentation.fragmentationOffset[1] = kSpsSize;
    fragmentation.fragmentationLength[1] = kPpsSize;
    fragmentation.fragmentationOffset[2] = kSpsSize + kPpsSize;
    fragmentation.fragmentationLength[2] =
        encoded_image._length - (kSpsSize + kPpsSize);
    const size_t kSpsNalHeader = 0x67;
    const size_t kPpsNalHeader = 0x68;
    const size_t kIdrNalHeader = 0x65;
    encoded_image._buffer[fragmentation.fragmentationOffset[0]] = kSpsNalHeader;
    encoded_image._buffer[fragmentation.fragmentationOffset[1]] = kPpsNalHeader;
    encoded_image._buffer[fragmentation.fragmentationOffset[2]] = kIdrNalHeader;
  } else {
    const size_t kNumSlices = 1;
    fragmentation.VerifyAndAllocateFragmentationHeader(kNumSlices);
    fragmentation.fragmentationOffset[0] = 0;
    fragmentation.fragmentationLength[0] = encoded_image._length;
    const size_t kNalHeader = 0x41;
    encoded_image._buffer[fragmentation.fragmentationOffset[0]] = kNalHeader;
  }
  uint8_t value = 0;
  int fragment_counter = 0;
  for (size_t i = 0; i < encoded_image._length; ++i) {
    if (fragment_counter == fragmentation.fragmentationVectorSize ||
        i != fragmentation.fragmentationOffset[fragment_counter]) {
      encoded_image._buffer[i] = value++;
    } else {
      ++fragment_counter;
    }
  }
  return callback_->Encoded(encoded_image, NULL, &fragmentation);
}

DelayedEncoder::DelayedEncoder(Clock* clock, int delay_ms)
    : test::FakeEncoder(clock),
      delay_ms_(delay_ms) {}

int32_t DelayedEncoder::Encode(const I420VideoFrame& input_image,
                               const CodecSpecificInfo* codec_specific_info,
                               const std::vector<VideoFrameType>* frame_types) {
  SleepMs(delay_ms_);
  return FakeEncoder::Encode(input_image, codec_specific_info, frame_types);
}
}  // namespace test
}  // namespace webrtc
<|endoftext|>


<commit_before>#include "core/log.h"
#include "client_file/api.h"
#include "network/api.h"
#include "replicate/api.h"
#include "voxelworld/api.h"
#include "interface/module.h"
#include "interface/server.h"
#include "interface/event.h"
#include "interface/mesh.h"
#include "interface/voxel.h"
#include "interface/noise.h"
#include <Scene.h>
#include <RigidBody.h>
#include <CollisionShape.h>
#include <ResourceCache.h>
#include <Context.h>
#include <StaticModel.h>
#include <Model.h>
#include <Material.h>
#include <Texture2D.h>
#include <Technique.h>
#include <cereal/archives/portable_binary.hpp>
#include <cereal/types/unordered_map.hpp>
#include <cereal/types/vector.hpp>

namespace digger {

namespace magic = Urho3D;
namespace pv = PolyVox;

using interface::Event;
using interface::VoxelInstance;

using namespace Urho3D;

struct Module: public interface::Module
{
	interface::Server *m_server;

	Module(interface::Server *server):
		interface::Module("digger"),
		m_server(server)
	{
	}

	~Module()
	{}

	void init()
	{
		m_server->sub_event(this, Event::t("core:start"));
		m_server->sub_event(this, Event::t("core:continue"));
		m_server->sub_event(this, Event::t("core:tick"));
		m_server->sub_event(this, Event::t("client_file:files_transmitted"));
		m_server->sub_event(this, Event::t("voxelworld:generation_request"));
	}

	void event(const Event::Type &type, const Event::Private *p)
	{
		EVENT_VOIDN("core:start", on_start)
		EVENT_VOIDN("core:continue", on_continue)
		EVENT_TYPEN("core:tick", on_tick, interface::TickEvent)
		EVENT_TYPEN("client_file:files_transmitted",
				on_files_transmitted, client_file::FilesTransmitted)
		EVENT_TYPEN("voxelworld:generation_request",
				on_generation_request, voxelworld::GenerationRequest)
	}

	void on_start()
	{
		m_server->access_scene([&](Scene *scene)
		{
			Context *context = scene->GetContext();
			ResourceCache *cache = context->GetSubsystem<ResourceCache>();

			{
				Node *node = scene->CreateChild("DirectionalLight");
				node->SetDirection(Vector3(-0.6f, -1.0f, 0.8f));
				Light *light = node->CreateComponent<Light>();
				light->SetLightType(LIGHT_DIRECTIONAL);
				light->SetCastShadows(true);
				light->SetBrightness(0.8);
				light->SetColor(Color(1.0, 1.0, 0.95));
			}
			{
				Node *node = scene->CreateChild("DirectionalLight");
				node->SetDirection(Vector3(0.3f, -1.0f, -0.4f));
				Light *light = node->CreateComponent<Light>();
				light->SetLightType(LIGHT_DIRECTIONAL);
				light->SetCastShadows(true);
				light->SetBrightness(0.2);
				light->SetColor(Color(0.7, 0.7, 1.0));
			}
			// Cheat (TODO: Fix)
			interface::VoxelRegistry *voxel_reg = nullptr;
			voxelworld::access(m_server, [&](voxelworld::Interface *ivoxelworld){
				voxel_reg = ivoxelworld->get_voxel_reg();
			});
			{
				Node *n = scene->CreateChild("Testbox");
				n->SetPosition(Vector3(30.0f, 30.0f, 40.0f));
				n->SetScale(Vector3(1.0f, 1.0f, 1.0f));

				/*int w = 1, h = 1, d = 1;
				ss_ data = "1";*/
				int w = 2, h = 2, d = 1;
				ss_ data = "1333";

				// Convert data to the actually usable voxel type id namespace
				// starting from VOXELTYPEID_UNDEFINED=0
				for(size_t i = 0; i < data.size(); i++){
					data[i] = data[i] - '0';
				}

				n->SetVar(StringHash("simple_voxel_data"), Variant(
						PODVector<uint8_t>((const uint8_t*)data.c_str(),
								data.size())));
				n->SetVar(StringHash("simple_voxel_w"), Variant(w));
				n->SetVar(StringHash("simple_voxel_h"), Variant(h));
				n->SetVar(StringHash("simple_voxel_d"), Variant(d));

				// Load the same model in here and give it to the physics
				// subsystem so that it can be collided to
				SharedPtr<Model> model(interface::
						create_8bit_voxel_physics_model(context, w, h, d, data,
						voxel_reg));

				RigidBody *body = n->CreateComponent<RigidBody>(LOCAL);
				body->SetFriction(0.75f);
				body->SetMass(1.0);
				CollisionShape *shape = n->CreateComponent<CollisionShape>(LOCAL);
				shape->SetConvexHull(model, 0, Vector3::ONE);
				//shape->SetTriangleMesh(model, 0, Vector3::ONE);
				//shape->SetBox(Vector3::ONE);
			}
		});
	}

	void on_continue()
	{
	}

	void update_scene()
	{
	}

	void on_tick(const interface::TickEvent &event)
	{
		/*m_server->access_scene([&](Scene *scene){
			Node *n = scene->GetChild("Testbox");
			auto p = n->GetPosition();
			log_v(MODULE, "Testbox: (%f, %f, %f)", p.x_, p.y_, p.z_);
		});*/
		static uint a = 0;
		if(((a++) % 50) == 0){
			m_server->access_scene([&](Scene *scene){
				Node *n = scene->GetChild("Testbox");
				n->SetRotation(Quaternion(30, 60, 90));
				n->SetPosition(Vector3(30.0f, 30.0f, 40.0f));
			});
		}
	}

	void on_files_transmitted(const client_file::FilesTransmitted &event)
	{
		network::access(m_server, [&](network::Interface *inetwork){
			inetwork->send(event.recipient, "core:run_script",
					"buildat.run_script_file(\"main/init.lua\")");
		});
	}

	void on_generation_request(const voxelworld::GenerationRequest &event)
	{
		log_v(MODULE, "on_generation_request(): section_p: (%i, %i, %i)",
				event.section_p.getX(), event.section_p.getY(),
				event.section_p.getZ());
		voxelworld::access(m_server, [&](voxelworld::Interface *ivoxelworld)
		{
			const pv::Vector3DInt16 &section_p = event.section_p;
			pv::Region region = ivoxelworld->get_section_region(section_p);

			pv::Vector3DInt32 p0 = region.getLowerCorner();
			pv::Vector3DInt32 p1 = region.getUpperCorner();

			log_t(MODULE, "on_generation_request(): p0: (%i, %i, %i)",
					p0.getX(), p0.getY(), p0.getZ());
			log_t(MODULE, "on_generation_request(): p1: (%i, %i, %i)",
					p1.getX(), p1.getY(), p1.getZ());

			interface::NoiseParams np(0, 20, interface::v3f(40,40,40), 0, 4, 0.5);

			auto lc = region.getLowerCorner();
			auto uc = region.getUpperCorner();
			for(int z = lc.getZ(); z <= uc.getZ(); z++){
				for(int y = lc.getY(); y <= uc.getY(); y++){
					for(int x = lc.getX(); x <= uc.getX(); x++){
						pv::Vector3DInt32 p(x, y, z);
						if(z > 37 && z < 50 && y > 20){
							ivoxelworld->set_voxel(p, VoxelInstance(1));
							continue;
						}
						if(x > 27 && x < 40 && y > 20){
							ivoxelworld->set_voxel(p, VoxelInstance(1));
							continue;
						}
						if(x > 18 && x < 25 && z >= 32 && z <= 37 &&
								y > 20 && y < 25){
							ivoxelworld->set_voxel(p, VoxelInstance(1));
							continue;
						}
						double a = interface::NoisePerlin2D(&np, x, z, 0);
						if(y < a+5){
							ivoxelworld->set_voxel(p, VoxelInstance(2));
						} else if(y < a+10){
							ivoxelworld->set_voxel(p, VoxelInstance(3));
						} else if(y < a+11){
							ivoxelworld->set_voxel(p, VoxelInstance(4));
						} else {
							ivoxelworld->set_voxel(p, VoxelInstance(1));
						}
					}
				}
			}
		});
	}
};

extern "C" {
	BUILDAT_EXPORT void* createModule_main(interface::Server *server){
		return (void*)(new Module(server));
	}
}
}
// vim: set noet ts=4 sw=4:
<commit_msg>games/digger/main: Make code thread-safe<commit_after>#include "core/log.h"
#include "client_file/api.h"
#include "network/api.h"
#include "replicate/api.h"
#include "voxelworld/api.h"
#include "interface/module.h"
#include "interface/server.h"
#include "interface/event.h"
#include "interface/mesh.h"
#include "interface/voxel.h"
#include "interface/noise.h"
#include <Scene.h>
#include <RigidBody.h>
#include <CollisionShape.h>
#include <ResourceCache.h>
#include <Context.h>
#include <StaticModel.h>
#include <Model.h>
#include <Material.h>
#include <Texture2D.h>
#include <Technique.h>
#include <cereal/archives/portable_binary.hpp>
#include <cereal/types/unordered_map.hpp>
#include <cereal/types/vector.hpp>

namespace digger {

namespace magic = Urho3D;
namespace pv = PolyVox;

using interface::Event;
using interface::VoxelInstance;

using namespace Urho3D;

struct Module: public interface::Module
{
	interface::Server *m_server;

	Module(interface::Server *server):
		interface::Module("digger"),
		m_server(server)
	{
	}

	~Module()
	{}

	void init()
	{
		m_server->sub_event(this, Event::t("core:start"));
		m_server->sub_event(this, Event::t("core:continue"));
		m_server->sub_event(this, Event::t("core:tick"));
		m_server->sub_event(this, Event::t("client_file:files_transmitted"));
		m_server->sub_event(this, Event::t("voxelworld:generation_request"));
	}

	void event(const Event::Type &type, const Event::Private *p)
	{
		EVENT_VOIDN("core:start", on_start)
		EVENT_VOIDN("core:continue", on_continue)
		EVENT_TYPEN("core:tick", on_tick, interface::TickEvent)
		EVENT_TYPEN("client_file:files_transmitted",
				on_files_transmitted, client_file::FilesTransmitted)
		EVENT_TYPEN("voxelworld:generation_request",
				on_generation_request, voxelworld::GenerationRequest)
	}

	void on_start()
	{
		m_server->access_scene([&](Scene *scene)
		{
			Context *context = scene->GetContext();
			ResourceCache *cache = context->GetSubsystem<ResourceCache>();

			{
				Node *node = scene->CreateChild("DirectionalLight");
				node->SetDirection(Vector3(-0.6f, -1.0f, 0.8f));
				Light *light = node->CreateComponent<Light>();
				light->SetLightType(LIGHT_DIRECTIONAL);
				light->SetCastShadows(true);
				light->SetBrightness(0.8);
				light->SetColor(Color(1.0, 1.0, 0.95));
			}
			{
				Node *node = scene->CreateChild("DirectionalLight");
				node->SetDirection(Vector3(0.3f, -1.0f, -0.4f));
				Light *light = node->CreateComponent<Light>();
				light->SetLightType(LIGHT_DIRECTIONAL);
				light->SetCastShadows(true);
				light->SetBrightness(0.2);
				light->SetColor(Color(0.7, 0.7, 1.0));
			}

			voxelworld::access(m_server, [&](voxelworld::Interface *ivoxelworld)
			{
				interface::VoxelRegistry *voxel_reg = ivoxelworld->get_voxel_reg();

				Node *n = scene->CreateChild("Testbox");
				n->SetPosition(Vector3(30.0f, 30.0f, 40.0f));
				n->SetScale(Vector3(1.0f, 1.0f, 1.0f));

				/*int w = 1, h = 1, d = 1;
				ss_ data = "1";*/
				int w = 2, h = 2, d = 1;
				ss_ data = "1333";

				// Convert data to the actually usable voxel type id namespace
				// starting from VOXELTYPEID_UNDEFINED=0
				for(size_t i = 0; i < data.size(); i++){
					data[i] = data[i] - '0';
				}

				n->SetVar(StringHash("simple_voxel_data"), Variant(
						PODVector<uint8_t>((const uint8_t*)data.c_str(),
								data.size())));
				n->SetVar(StringHash("simple_voxel_w"), Variant(w));
				n->SetVar(StringHash("simple_voxel_h"), Variant(h));
				n->SetVar(StringHash("simple_voxel_d"), Variant(d));

				// Load the same model in here and give it to the physics
				// subsystem so that it can be collided to
				SharedPtr<Model> model(interface::
						create_8bit_voxel_physics_model(context, w, h, d, data,
						voxel_reg));

				RigidBody *body = n->CreateComponent<RigidBody>(LOCAL);
				body->SetFriction(0.75f);
				body->SetMass(1.0);
				CollisionShape *shape = n->CreateComponent<CollisionShape>(LOCAL);
				shape->SetConvexHull(model, 0, Vector3::ONE);
				//shape->SetTriangleMesh(model, 0, Vector3::ONE);
				//shape->SetBox(Vector3::ONE);
			});
		});
	}

	void on_continue()
	{
	}

	void update_scene()
	{
	}

	void on_tick(const interface::TickEvent &event)
	{
		/*m_server->access_scene([&](Scene *scene){
			Node *n = scene->GetChild("Testbox");
			auto p = n->GetPosition();
			log_v(MODULE, "Testbox: (%f, %f, %f)", p.x_, p.y_, p.z_);
		});*/
		static uint a = 0;
		if(((a++) % 50) == 0){
			m_server->access_scene([&](Scene *scene){
				Node *n = scene->GetChild("Testbox");
				n->SetRotation(Quaternion(30, 60, 90));
				n->SetPosition(Vector3(30.0f, 30.0f, 40.0f));
			});
		}
	}

	void on_files_transmitted(const client_file::FilesTransmitted &event)
	{
		network::access(m_server, [&](network::Interface *inetwork){
			inetwork->send(event.recipient, "core:run_script",
					"buildat.run_script_file(\"main/init.lua\")");
		});
	}

	void on_generation_request(const voxelworld::GenerationRequest &event)
	{
		log_v(MODULE, "on_generation_request(): section_p: (%i, %i, %i)",
				event.section_p.getX(), event.section_p.getY(),
				event.section_p.getZ());
		voxelworld::access(m_server, [&](voxelworld::Interface *ivoxelworld)
		{
			const pv::Vector3DInt16 &section_p = event.section_p;
			pv::Region region = ivoxelworld->get_section_region(section_p);

			pv::Vector3DInt32 p0 = region.getLowerCorner();
			pv::Vector3DInt32 p1 = region.getUpperCorner();

			log_t(MODULE, "on_generation_request(): p0: (%i, %i, %i)",
					p0.getX(), p0.getY(), p0.getZ());
			log_t(MODULE, "on_generation_request(): p1: (%i, %i, %i)",
					p1.getX(), p1.getY(), p1.getZ());

			interface::NoiseParams np(0, 20, interface::v3f(40,40,40), 0, 4, 0.5);

			auto lc = region.getLowerCorner();
			auto uc = region.getUpperCorner();
			for(int z = lc.getZ(); z <= uc.getZ(); z++){
				for(int y = lc.getY(); y <= uc.getY(); y++){
					for(int x = lc.getX(); x <= uc.getX(); x++){
						pv::Vector3DInt32 p(x, y, z);
						if(z > 37 && z < 50 && y > 20){
							ivoxelworld->set_voxel(p, VoxelInstance(1));
							continue;
						}
						if(x > 27 && x < 40 && y > 20){
							ivoxelworld->set_voxel(p, VoxelInstance(1));
							continue;
						}
						if(x > 18 && x < 25 && z >= 32 && z <= 37 &&
								y > 20 && y < 25){
							ivoxelworld->set_voxel(p, VoxelInstance(1));
							continue;
						}
						double a = interface::NoisePerlin2D(&np, x, z, 0);
						if(y < a+5){
							ivoxelworld->set_voxel(p, VoxelInstance(2));
						} else if(y < a+10){
							ivoxelworld->set_voxel(p, VoxelInstance(3));
						} else if(y < a+11){
							ivoxelworld->set_voxel(p, VoxelInstance(4));
						} else {
							ivoxelworld->set_voxel(p, VoxelInstance(1));
						}
					}
				}
			}
		});
	}
};

extern "C" {
	BUILDAT_EXPORT void* createModule_main(interface::Server *server){
		return (void*)(new Module(server));
	}
}
}
// vim: set noet ts=4 sw=4:
<|endoftext|>


<commit_before>#include "ModelOBJ.h"

#include "OBJLoader.h"

namespace cs557_OBJModel
{

	static const string vs_string_410 =
		"#version 410 core                                                 \n"
		"                                                                   \n"
		"uniform mat4 projectionMatrix;                                    \n"
		"uniform mat4 viewMatrix;                                           \n"
		"uniform mat4 modelMatrix;                                          \n"
		"in vec3 in_Position;                                               \n"
		"in vec2 in_Texture;                                                \n"
		"in vec3 in_Normal;                                                  \n"
		"out vec3 pass_Color;                                               \n"
		"out vec2 pass_Texture;												\n"
		"                                                                  \n"
		"void main(void)                                                   \n"
		"{                                                                 \n"
		"    gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(in_Position, 1.0);  \n"
		"    pass_Color = in_Normal;                                         \n"
		"    pass_Texture = in_Texture;                                         \n"
		"}                                                                 \n";

	// Fragment shader source code. This determines the colors in the fragment generated in the shader pipeline. In this case, it colors the inside of our triangle specified by our vertex shader.
	static const string fs_string_410 =
		"#version 410 core                                                 \n"
		"                                                                  \n"
		"in vec3 pass_Color;                                                 \n"
		"in vec2 pass_Texture;												\n"
		"out vec4 color;                                                    \n"
		"void main(void)                                                   \n"
		"{                                                                 \n"
		"    color = vec4(pass_Color, 1.0);                               \n"
		"}                                                                 \n";

};

using namespace cs557_OBJModel;

/*
Load an OBJ model from file
@param path_and_filename - number of rows
@param shader_program - overwrite the default shader program by passing a hander to the constructor
*/
void cs557::OBJModel::create(string path_and_filename, int shader_program)
{
	program = -1;
	_N = 0;
	_I = 0;

	// This overwrite the default shader program
	if(shader_program != -1){
		program = shader_program;
	}

	float center_x = 0.0;
	float center_y = 0.0;
	float center_z = 0.0;

	std::vector<std::pair<glm::vec3, glm::vec2> > points; // points and texture coordinates
	std::vector<glm::vec3> normals;
	std::vector<int> indices;

	// create a shader program only if the progrm was not overwritten.
	if(program == -1)
		program = cs557::CreateShaderProgram(vs_string_410, fs_string_410);

	// Find the id's of the related variable name in your shader code.
	projMatrixLocation = glGetUniformLocation(program, "projectionMatrix"); // Get the location of our projection matrix in the shader
	viewMatrixLocation = glGetUniformLocation(program, "viewMatrix"); // Get the location of our view matrix in the shader
	modelMatrixLocation = glGetUniformLocation(program, "modelMatrix"); // Get the location of our model matrix in the shader
	int pos_location = glGetAttribLocation(program, "in_Position");
	int norm_location = glGetAttribLocation(program, "in_Normal");
	int tex_location = glGetAttribLocation(program, "in_Texture");

	// Load the geometry from file.
	objl::Loader loader;
	loader.LoadFile(path_and_filename);

	int size = loader.LoadedMeshes.size();

	if(size > 0)
	{

		objl::Mesh curMesh = loader.LoadedMeshes[0];

		for (int j = 0; j < curMesh.Vertices.size(); j++)
		{
			points.push_back(make_pair( glm::vec3(curMesh.Vertices[j].Position.X, curMesh.Vertices[j].Position.Y, curMesh.Vertices[j].Position.Z),
			 							glm::vec2(curMesh.Vertices[j].TextureCoordinate.X, curMesh.Vertices[j].TextureCoordinate.Y )));
			normals.push_back(glm::vec3(curMesh.Vertices[j].Normal.X, curMesh.Vertices[j].Normal.Y, curMesh.Vertices[j].Normal.Z) );
		}

		for (int j = 0; j < curMesh.Indices.size(); j++)
		{
			indices.push_back(curMesh.Indices[j]);
		}

		_I = curMesh.Indices.size();
		_N = points.size();

		// create a vertex buffer object
		cs557::CreateVertexObjectsIndexed53(vaoID, vboID, iboID, &points[0].first.x, &normals[0].x, _N, &indices[0], _I, pos_location, tex_location, norm_location );

		//glBindAttribLocation(program, pos_location, "in_Position");
		//glBindAttribLocation(program, norm_location, "in_Normal");
		//glBindAttribLocation(program, tex_location, "in_Texture");
	}
}

/*
Draw the coordinate system
@param viewMatrix - a view matrix object
@param modelMatrix - a model matrix object.
*/
void cs557::OBJModel::draw(glm::mat4 projectionMatrix, glm::mat4 viewMatrix, glm::mat4 modelMatrix )
{

	// Enable the shader program
	glUseProgram(program);

	// this changes the camera location
	glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, &viewMatrix[0][0]); // send the view matrix to our shader
	glUniformMatrix4fv(modelMatrixLocation, 1, GL_FALSE, &modelMatrix[0][0]); // send the model matrix to our shader
	glUniformMatrix4fv(projMatrixLocation, 1, GL_FALSE, &projectionMatrix[0][0]); // send the projection matrix to our shader

	 // Bind the buffer and switch it to an active buffer
	glBindVertexArray(vaoID[0]);

	// Draw the triangles
 	glDrawElements(GL_TRIANGLES, _N, GL_UNSIGNED_INT, 0);

	// Unbind our Vertex Array Object
	glBindVertexArray(0);

	// Unbind the shader program
	glUseProgram(0);

}

<commit_msg>Bug fixes<commit_after>#include "ModelOBJ.h"

#include "OBJLoader.h"

namespace cs557_OBJModel
{

	static const string vs_string_410 =
		"#version 410 core                                                 \n"
		"                                                                   \n"
		"uniform mat4 projectionMatrix;                                    \n"
		"uniform mat4 viewMatrix;                                           \n"
		"uniform mat4 modelMatrix;                                          \n"
		"in vec3 in_Position;                                               \n"
		"in vec2 in_Texture;                                                \n"
		"in vec3 in_Normal;                                                  \n"
		"out vec3 pass_Color;                                               \n"
		"out vec2 pass_Texture;												\n"
		"                                                                  \n"
		"void main(void)                                                   \n"
		"{                                                                 \n"
		"    gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(in_Position, 1.0);  \n"
		"    pass_Color = in_Normal;                                         \n"
		"    pass_Texture = in_Texture;                                         \n"
		"}                                                                 \n";

	// Fragment shader source code. This determines the colors in the fragment generated in the shader pipeline. In this case, it colors the inside of our triangle specified by our vertex shader.
	static const string fs_string_410 =
		"#version 410 core                                                 \n"
		"                                                                  \n"
		"in vec3 pass_Color;                                                 \n"
		"in vec2 pass_Texture;												\n"
		"out vec4 color;                                                    \n"
		"void main(void)                                                   \n"
		"{                                                                 \n"
		"    color = vec4(pass_Color, 1.0);                               \n"
		"}                                                                 \n";

};

using namespace cs557_OBJModel;

/*
Load an OBJ model from file
@param path_and_filename - number of rows
@param shader_program - overwrite the default shader program by passing a hander to the constructor
*/
void cs557::OBJModel::create(string path_and_filename, int shader_program)
{
	program = -1;
	_N = 0;
	_I = 0;

	// This overwrite the default shader program
	if(shader_program != -1){
		program = shader_program;
	}

	float center_x = 0.0;
	float center_y = 0.0;
	float center_z = 0.0;

	std::vector<std::pair<glm::vec3, glm::vec2> > points; // points and texture coordinates
	std::vector<glm::vec3> normals;
	std::vector<int> indices;

	// create a shader program only if the progrm was not overwritten.
	if(program == -1)
		program = cs557::CreateShaderProgram(vs_string_410, fs_string_410);

	// Find the id's of the related variable name in your shader code.
	projMatrixLocation = glGetUniformLocation(program, "projectionMatrix"); // Get the location of our projection matrix in the shader
	viewMatrixLocation = glGetUniformLocation(program, "viewMatrix"); // Get the location of our view matrix in the shader
	modelMatrixLocation = glGetUniformLocation(program, "modelMatrix"); // Get the location of our model matrix in the shader
	int pos_location = glGetAttribLocation(program, "in_Position");
	int norm_location = glGetAttribLocation(program, "in_Normal");
	int tex_location = glGetAttribLocation(program, "in_Texture");

	// Load the geometry from file.
	objl::Loader loader;
	loader.LoadFile(path_and_filename);

	int size = loader.LoadedMeshes.size();

	for(int i=0; i<size; i++)
	{

		objl::Mesh curMesh = loader.LoadedMeshes[i];

		for (int j = 0; j < curMesh.Vertices.size(); j++)
		{
			points.push_back(make_pair( glm::vec3(curMesh.Vertices[j].Position.X, curMesh.Vertices[j].Position.Y, curMesh.Vertices[j].Position.Z),
			 							glm::vec2(curMesh.Vertices[j].TextureCoordinate.X, curMesh.Vertices[j].TextureCoordinate.Y )));
			normals.push_back(glm::vec3(curMesh.Vertices[j].Normal.X, curMesh.Vertices[j].Normal.Y, curMesh.Vertices[j].Normal.Z) );
		}

		for (int j = 0; j < curMesh.Indices.size(); j++)
		{
			indices.push_back(curMesh.Indices[j]);
		}
		//glBindAttribLocation(program, pos_location, "in_Position");
		//glBindAttribLocation(program, norm_location, "in_Normal");
		//glBindAttribLocation(program, tex_location, "in_Texture");
	}
	_I = indices.size();
	_N = points.size();

	// create a vertex buffer object
	cs557::CreateVertexObjectsIndexed53(vaoID, vboID, iboID, &points[0].first.x, &normals[0].x, _N, &indices[0], _I, pos_location, tex_location, norm_location );

}

/*
Draw the coordinate system
@param viewMatrix - a view matrix object
@param modelMatrix - a model matrix object.
*/
void cs557::OBJModel::draw(glm::mat4 projectionMatrix, glm::mat4 viewMatrix, glm::mat4 modelMatrix )
{

	// Enable the shader program
	glUseProgram(program);

	// this changes the camera location
	glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, &viewMatrix[0][0]); // send the view matrix to our shader
	glUniformMatrix4fv(modelMatrixLocation, 1, GL_FALSE, &modelMatrix[0][0]); // send the model matrix to our shader
	glUniformMatrix4fv(projMatrixLocation, 1, GL_FALSE, &projectionMatrix[0][0]); // send the projection matrix to our shader

	 // Bind the buffer and switch it to an active buffer
	glBindVertexArray(vaoID[0]);

	// Draw the triangles
 	glDrawElements(GL_TRIANGLES, _I, GL_UNSIGNED_INT, 0);

	// Unbind our Vertex Array Object
	glBindVertexArray(0);

	// Unbind the shader program
	glUseProgram(0);

}

<|endoftext|>