<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

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

// Helper functions for dumping Graphs, GraphDefs, and FunctionDefs to files for
// debugging.

#include "tensorflow/compiler/tf2xla/dump_graph.h"

#include "tensorflow/compiler/tf2xla/dump_graph_flags.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/mutex.h"

namespace tensorflow {
namespace dump_graph {

namespace {

struct NameCounts {
  mutex counts_mutex;
  std::unordered_map<string, int> counts;
};

string MakeUniquePath(string name) {
  static NameCounts& instance = *new NameCounts;

  // Remove illegal characters from `name`.
  for (int i = 0; i < name.size(); ++i) {
    if (name[i] == '/') {
      name[i] = '_';
    }
  }

  int count;
  {
    mutex_lock lock(instance.counts_mutex);
    count = instance.counts[name]++;
  }

  legacy_flags::DumpGraphFlags* flags = legacy_flags::GetDumpGraphFlags();
  string path = strings::StrCat(flags->tf_dump_graph_prefix, "/", name);
  if (count > 0) {
    strings::StrAppend(&path, "_", count);
  }
  strings::StrAppend(&path, ".pbtxt");
  return path;
}

}  // anonymous namespace

string DumpGraphDefToFile(const string& name, GraphDef const& graph_def) {
  string path = MakeUniquePath(name);
  TF_CHECK_OK(WriteTextProto(Env::Default(), path, graph_def));
  return path;
}

string DumpGraphToFile(const string& name, Graph const& graph,
                       const FunctionLibraryDefinition* flib_def) {
  GraphDef graph_def;
  graph.ToGraphDef(&graph_def);
  if (flib_def) {
    *graph_def.mutable_library() = flib_def->ToProto();
  }
  return DumpGraphDefToFile(name, graph_def);
}

string DumpFunctionDefToFile(const string& name, FunctionDef const& fdef) {
  string path = MakeUniquePath(name);
  TF_CHECK_OK(WriteTextProto(Env::Default(), path, fdef));
  return path;
}

}  // namespace dump_graph
}  // namespace tensorflow
<commit_msg>Scrub names in dump_graph.cc for .?[] as well.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

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

// Helper functions for dumping Graphs, GraphDefs, and FunctionDefs to files for
// debugging.

#include "tensorflow/compiler/tf2xla/dump_graph.h"

#include "tensorflow/compiler/tf2xla/dump_graph_flags.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/mutex.h"

namespace tensorflow {
namespace dump_graph {

namespace {

struct NameCounts {
  mutex counts_mutex;
  std::unordered_map<string, int> counts;
};

string MakeUniquePath(string name) {
  static NameCounts& instance = *new NameCounts;

  // Remove illegal characters from `name`.
  for (int i = 0; i < name.size(); ++i) {
    char ch = name[i];
    if (ch == '/' || ch == '[' || ch == ']' || ch == '*' || ch == '?') {
      name[i] = '_';
    }
  }

  int count;
  {
    mutex_lock lock(instance.counts_mutex);
    count = instance.counts[name]++;
  }

  legacy_flags::DumpGraphFlags* flags = legacy_flags::GetDumpGraphFlags();
  string path = strings::StrCat(flags->tf_dump_graph_prefix, "/", name);
  if (count > 0) {
    strings::StrAppend(&path, "_", count);
  }
  strings::StrAppend(&path, ".pbtxt");
  return path;
}

}  // anonymous namespace

string DumpGraphDefToFile(const string& name, GraphDef const& graph_def) {
  string path = MakeUniquePath(name);
  TF_CHECK_OK(WriteTextProto(Env::Default(), path, graph_def));
  return path;
}

string DumpGraphToFile(const string& name, Graph const& graph,
                       const FunctionLibraryDefinition* flib_def) {
  GraphDef graph_def;
  graph.ToGraphDef(&graph_def);
  if (flib_def) {
    *graph_def.mutable_library() = flib_def->ToProto();
  }
  return DumpGraphDefToFile(name, graph_def);
}

string DumpFunctionDefToFile(const string& name, FunctionDef const& fdef) {
  string path = MakeUniquePath(name);
  TF_CHECK_OK(WriteTextProto(Env::Default(), path, fdef));
  return path;
}

}  // namespace dump_graph
}  // namespace tensorflow
<|endoftext|>


<commit_before><commit_msg>Provide more secure handling of zoombox in hist painter<commit_after><|endoftext|>


<commit_before>#include <SDL2/SDL.h>
#include <iostream>

#include "core/log.h"
#include "core/str.h"

#include "render/shader.h"
#include "render/spriterender.h"

#include "core/interpolate.h"
#include "core/os.h"
#include "core/componentsystem.h"
#include "core/filesystemimagegenerator.h"
#include "core/filesystemdefaultshaders.h"
#include "core/proto.h"

#include "render/debuggl.h"
#include "render/fonts.h"
#include "render/init.h"
#include "render/fontcache.h"
#include "render/scalablesprite.h"
#include "render/shaderattribute2d.h"
#include "render/texturecache.h"
#include "render/viewport.h"

#include "gui/root.h"
#include "window/key.h"

#include "engine/loadworld.h"
#include "engine/systems.h"
#include "core/duk.h"
#include "engine/dukintegration.h"
#include "engine/dukmathbindings.h"
#include "engine/dukprint.h"
#include "engine/input.h"
#include "engine/objectemplate.h"
#include "engine/components.h"

#include "window/imguilibrary.h"
#include "window/imgui_ext.h"
#include "window/filesystem.h"

#include "imgui/imgui.h"

#include "gaf_game.h"

LOG_SPECIFY_DEFAULT_LOGGER("engine")

game::Game
LoadGameData(FileSystem* fs)
{
  game::Game game;
  const auto err = LoadProtoJson(fs, &game, "gamedata.json");
  if(!err.empty())
  {
    LOG_ERROR("Failed to load gamedata.json: " << err);
  }
  return game;
}

struct RunResult
{
  bool        ok;
  std::string message;

  static const RunResult
  Ok()
  {
    return RunResult{true, ""};
  };

  static const RunResult
  Error(const std::string& message)
  {
    return RunResult{false, message};
  };

 private:
  RunResult(bool b, const std::string& str)
      : ok(b)
      , message(str)
  {
  }
};

RunResult
RunMainScriptFile(Duk* duk, FileSystem* fs, const std::string& path)
{
  std::string content;
  const bool  loaded = fs->ReadFileToString(path, &content);
  if(!loaded)
  {
    const std::string error_message = Str() << "Unable to open " << path
                                            << " for running";
    LOG_ERROR(error_message);
    return RunResult::Error(error_message);
  }
  std::string error;
  const bool  eval = duk->EvalString(content, path, &error, nullptr);
  if(!eval)
  {
    const std::string error_message = Str() << "Failed to run " << path << ": "
                                            << error;
    LOG_ERROR(error_message);
    return RunResult::Error(error_message);
  }

  return RunResult::Ok();
}

int
main(int argc, char** argv)
{
  if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO) < 0)
  {
    LOG_ERROR("Failed to init SDL: " << SDL_GetError());
    return -1;
  }

  SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_STEREO, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
  SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 1);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);

  const auto current_directory = GetCurrentDirectory();
  FileSystem file_system;
  file_system.SetWrite(
      std::make_shared<FileSystemWriteFolder>(current_directory));
  FileSystemRootFolder::AddRoot(&file_system, current_directory);
  FileSystemImageGenerator::AddRoot(&file_system, "img-plain");
  FileSystemDefaultShaders::AddRoot(&file_system, "shaders");
  auto         catalog = FileSystemRootCatalog::AddRoot(&file_system);
  TextureCache cache{&file_system};

  game::Game gamedata = LoadGameData(&file_system);

  int width  = 800;
  int height = 600;

  SDL_Window* window = SDL_CreateWindow(
      gamedata.title.c_str(),
      SDL_WINDOWPOS_UNDEFINED,
      SDL_WINDOWPOS_UNDEFINED,
      width,
      height,
      SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);

  if(window == NULL)
  {
    LOG_ERROR("Failed to create window " << SDL_GetError());
    return -1;
  }

  const auto pref_path = GetPrefPath();

  ImguiLibrary imgui{window, pref_path};

  SDL_GL_CreateContext(window);
  Init init{SDL_GL_GetProcAddress, Init::BlendHack::EnableHack};

  if(init.ok == false)
  {
    return -4;
  }

  SetupOpenglDebug();

  // todo: update theese during runtime
  std::string crash_message_string;
  bool        has_crashed = false;

  Input input;

  for(const auto& bind : gamedata.binds)
  {
    auto key = ToKey(bind.key);
    if(key == Key::INVALID)
    {
      LOG_ERROR("Invalid key: " << bind.key);
      key = Key::UNBOUND;
    }

    input.Add(std::make_shared<BoundVar>(bind.name, key));
  }

  Shader shader;
  attributes2d::PrebindShader(&shader);
  shader.Load(&file_system, "shaders/sprite");
  SpriteRenderer renderer(&shader);
  FontCache      font_cache{&file_system, &cache};

  // Sprite player(cache.GetTexture("player.png"));
  // objects.Add(&player);

  Duk duk;
  AddPrint(&duk);
  BindMath(&duk);
  Input::Bind(&duk);

  Systems    systems;
  World      world{&systems};
  Components components{&world.reg};
  AddSystems(&systems, &duk, &components);
  ObjectCreator templates;
  LoadTemplatesButOnlyNames(gamedata, &templates);

  DukIntegration integration{&systems, &world, &duk, &templates, &components};
  const auto error_run_main = RunMainScriptFile(&duk, &file_system, "main.js");
  if(!error_run_main.ok)
  {
    has_crashed          = true;
    crash_message_string = error_run_main.message;
  }
  LoadTemplates(
      gamedata, &templates, &integration.Registry(), &cache, &components);

  LoadWorld(
      &file_system,
      &world,
      &integration.Registry(),
      "world.json",
      &templates,
      duk.AsContext(),
      &duk);

  const mat4f projection = init.GetOrthoProjection(width, height);
  Use(&shader);
  shader.SetUniform(shader.GetUniform("image"), 0);
  shader.SetUniform(shader.GetUniform("projection"), projection);

  Viewport viewport{
      Recti::FromWidthHeight(width, height).SetBottomLeftToCopy(0, 0)};
  viewport.Activate();

  Uint64 now  = SDL_GetPerformanceCounter();
  Uint64 last = 0;

  SDL_StartTextInput();

  bool running = true;

  int window_mouse_x = 0;
  int window_mouse_y = 0;
  SDL_GetMouseState(&window_mouse_x, &window_mouse_y);
  bool mouse_lmb_down = false;

  integration.BindKeys(&duk, input);

  while(running)
  {
    last           = now;
    now            = SDL_GetPerformanceCounter();
    const float dt = (now - last) * 1.0f / SDL_GetPerformanceFrequency();
    SDL_Event   e;

    imgui.StartNewFrame();

    if(!has_crashed)
    {
      try
      {
        world.Update(dt);
      }
      catch(const std::exception& ex)
      {
        has_crashed          = true;
        crash_message_string = ex.what();
      }
    }

    input.UpdateState();

    while(SDL_PollEvent(&e) != 0)
    {
      if(e.type == SDL_QUIT)
      {
        running = false;
      }
      if(has_crashed)
      {
        imgui.ProcessEvents(&e);
        if(e.type == SDL_KEYUP)
        {
          const auto key = ToKey(e.key.keysym);
          if(key == Key::ESCAPE)
          {
            running = false;
          }
        }
      }
      else
      {
        if(e.type == SDL_MOUSEMOTION)
        {
          window_mouse_x = e.motion.x;
          window_mouse_y = e.motion.y;
        }
        else if(e.type == SDL_KEYUP || e.type == SDL_KEYDOWN)
        {
          const bool down = e.type == SDL_KEYDOWN;
          const auto key  = ToKey(e.key.keysym);
          input.SetKeyState(key, down ? 1.0f : 0.0f);
        }
        else if(e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_MOUSEBUTTONUP)
        {
          const bool down = e.type == SDL_MOUSEBUTTONDOWN;
          window_mouse_x  = e.button.x;
          window_mouse_y  = e.button.y;
          if(e.button.button == SDL_BUTTON_LEFT)
          {
            mouse_lmb_down = down;
          }
        }
        else if(e.type == SDL_TEXTINPUT)
        {
          const std::string& input = e.text.text;
        }
      }
    }

    if(has_crashed == false)
    {
      integration.BindKeys(&duk, input);
    }

    if(has_crashed)
    {
      // todo: fix crash rendering, perhaps by using a debug gui or imgui
      // nothing much is required just a better overflow detection
      // when rendering the error, perhaps making the error more visible
      // though clicking around and debugging might be useful...
      init.ClearScreen(Color::CornflowerBlue);

      if(BeginFixedOverlay(ImguiCorner::Center, "Crashed"))
      {
        ImGui::TextDisabled("%s", crash_message_string.c_str());
        /*ImGui::InputTextMultiline(
            "##source",
            crash_message_string.c_str(),
            crash_message_string.length(),
            ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16),
            ImGuiInputTextFlags_ReadOnly); */
        if(ImGui::Button("Quit"))
        {
          running = false;
        }
        ImGui::End();
      }
    }
    else
    {
      init.ClearScreen(Color::DarkslateGray);
      world.Draw(&renderer);
    }

    imgui.Render();
    SDL_GL_SwapWindow(window);

    world.reg.RemoveRemoved();
  }

  SDL_DestroyWindow(window);
  SDL_Quit();
  return 0;
}
<commit_msg>resize window functionality<commit_after>#include <SDL2/SDL.h>
#include <iostream>

#include "core/log.h"
#include "core/str.h"

#include "render/shader.h"
#include "render/spriterender.h"

#include "core/interpolate.h"
#include "core/os.h"
#include "core/componentsystem.h"
#include "core/filesystemimagegenerator.h"
#include "core/filesystemdefaultshaders.h"
#include "core/proto.h"

#include "render/debuggl.h"
#include "render/fonts.h"
#include "render/init.h"
#include "render/fontcache.h"
#include "render/scalablesprite.h"
#include "render/shaderattribute2d.h"
#include "render/texturecache.h"
#include "render/viewport.h"

#include "gui/root.h"
#include "window/key.h"

#include "engine/loadworld.h"
#include "engine/systems.h"
#include "core/duk.h"
#include "engine/dukintegration.h"
#include "engine/dukmathbindings.h"
#include "engine/dukprint.h"
#include "engine/input.h"
#include "engine/objectemplate.h"
#include "engine/components.h"

#include "window/imguilibrary.h"
#include "window/imgui_ext.h"
#include "window/filesystem.h"

#include "imgui/imgui.h"

#include "gaf_game.h"

LOG_SPECIFY_DEFAULT_LOGGER("engine")

game::Game
LoadGameData(FileSystem* fs)
{
  game::Game game;
  const auto err = LoadProtoJson(fs, &game, "gamedata.json");
  if(!err.empty())
  {
    LOG_ERROR("Failed to load gamedata.json: " << err);
  }
  return game;
}

struct RunResult
{
  bool        ok;
  std::string message;

  static const RunResult
  Ok()
  {
    return RunResult{true, ""};
  };

  static const RunResult
  Error(const std::string& message)
  {
    return RunResult{false, message};
  };

 private:
  RunResult(bool b, const std::string& str)
      : ok(b)
      , message(str)
  {
  }
};

RunResult
RunMainScriptFile(Duk* duk, FileSystem* fs, const std::string& path)
{
  std::string content;
  const bool  loaded = fs->ReadFileToString(path, &content);
  if(!loaded)
  {
    const std::string error_message = Str() << "Unable to open " << path
                                            << " for running";
    LOG_ERROR(error_message);
    return RunResult::Error(error_message);
  }
  std::string error;
  const bool  eval = duk->EvalString(content, path, &error, nullptr);
  if(!eval)
  {
    const std::string error_message = Str() << "Failed to run " << path << ": "
                                            << error;
    LOG_ERROR(error_message);
    return RunResult::Error(error_message);
  }

  return RunResult::Ok();
}

struct ViewportHandler
{
  Init*                init;
  std::vector<Shader*> shaders;

  explicit ViewportHandler(Init* i)
      : init(i)
  {
  }

  void
  Add(Shader* shader)
  {
    shaders.emplace_back(shader);
  }

  void
  SetSize(int width, int height)
  {
    const mat4f projection = init->GetOrthoProjection(width, height);
    for(auto* shader : shaders)
    {
      shader->SetUniform(shader->GetUniform("projection"), projection);
    }

    Viewport viewport{
        Recti::FromWidthHeight(width, height).SetBottomLeftToCopy(0, 0)};
    viewport.Activate();
  }
};

int
main(int argc, char** argv)
{
  if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO) < 0)
  {
    LOG_ERROR("Failed to init SDL: " << SDL_GetError());
    return -1;
  }

  SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 4);
  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, 0);
  SDL_GL_SetAttribute(SDL_GL_STEREO, 0);
  SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
  SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 1);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
  SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);

  const auto current_directory = GetCurrentDirectory();
  FileSystem file_system;
  file_system.SetWrite(
      std::make_shared<FileSystemWriteFolder>(current_directory));
  FileSystemRootFolder::AddRoot(&file_system, current_directory);
  FileSystemImageGenerator::AddRoot(&file_system, "img-plain");
  FileSystemDefaultShaders::AddRoot(&file_system, "shaders");
  auto         catalog = FileSystemRootCatalog::AddRoot(&file_system);
  TextureCache cache{&file_system};

  game::Game gamedata = LoadGameData(&file_system);

  int window_width  = 800;
  int window_height = 600;

  SDL_Window* window = SDL_CreateWindow(
      gamedata.title.c_str(),
      SDL_WINDOWPOS_UNDEFINED,
      SDL_WINDOWPOS_UNDEFINED,
      window_width,
      window_height,
      SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

  if(window == NULL)
  {
    LOG_ERROR("Failed to create window " << SDL_GetError());
    return -1;
  }

  const auto pref_path = GetPrefPath();

  ImguiLibrary imgui{window, pref_path};

  SDL_GL_CreateContext(window);
  Init init{SDL_GL_GetProcAddress, Init::BlendHack::EnableHack};

  if(init.ok == false)
  {
    return -4;
  }

  SetupOpenglDebug();

  // todo: update theese during runtime
  std::string crash_message_string;
  bool        has_crashed = false;

  Input input;

  for(const auto& bind : gamedata.binds)
  {
    auto key = ToKey(bind.key);
    if(key == Key::INVALID)
    {
      LOG_ERROR("Invalid key: " << bind.key);
      key = Key::UNBOUND;
    }

    input.Add(std::make_shared<BoundVar>(bind.name, key));
  }

  Shader shader;
  attributes2d::PrebindShader(&shader);
  shader.Load(&file_system, "shaders/sprite");
  SpriteRenderer renderer(&shader);
  FontCache      font_cache{&file_system, &cache};

  // Sprite player(cache.GetTexture("player.png"));
  // objects.Add(&player);

  Duk duk;
  AddPrint(&duk);
  BindMath(&duk);
  Input::Bind(&duk);

  Systems    systems;
  World      world{&systems};
  Components components{&world.reg};
  AddSystems(&systems, &duk, &components);
  ObjectCreator templates;
  LoadTemplatesButOnlyNames(gamedata, &templates);

  DukIntegration integration{&systems, &world, &duk, &templates, &components};
  const auto error_run_main = RunMainScriptFile(&duk, &file_system, "main.js");
  if(!error_run_main.ok)
  {
    has_crashed          = true;
    crash_message_string = error_run_main.message;
  }
  LoadTemplates(
      gamedata, &templates, &integration.Registry(), &cache, &components);

  LoadWorld(
      &file_system,
      &world,
      &integration.Registry(),
      "world.json",
      &templates,
      duk.AsContext(),
      &duk);

  Use(&shader);
  shader.SetUniform(shader.GetUniform("image"), 0);

  ViewportHandler viewport_handler{&init};
  viewport_handler.Add(&shader);

  viewport_handler.SetSize(window_width, window_height);

  Uint64 now  = SDL_GetPerformanceCounter();
  Uint64 last = 0;

  SDL_StartTextInput();

  bool running = true;

  int window_mouse_x = 0;
  int window_mouse_y = 0;
  SDL_GetMouseState(&window_mouse_x, &window_mouse_y);
  bool mouse_lmb_down = false;

  integration.BindKeys(&duk, input);

  while(running)
  {
    last           = now;
    now            = SDL_GetPerformanceCounter();
    const float dt = (now - last) * 1.0f / SDL_GetPerformanceFrequency();
    SDL_Event   e;

    imgui.StartNewFrame();

    if(!has_crashed)
    {
      try
      {
        world.Update(dt);
      }
      catch(const std::exception& ex)
      {
        has_crashed          = true;
        crash_message_string = ex.what();
      }
    }

    input.UpdateState();

    while(SDL_PollEvent(&e) != 0)
    {
      if(e.type == SDL_QUIT)
      {
        running = false;
      }
      if(e.type == SDL_WINDOWEVENT_SIZE_CHANGED)
      {
        SDL_GetWindowSize(window, &window_width, &window_height);
        viewport_handler.SetSize(window_width, window_height);
      }
      if(has_crashed)
      {
        imgui.ProcessEvents(&e);
        if(e.type == SDL_KEYUP)
        {
          const auto key = ToKey(e.key.keysym);
          if(key == Key::ESCAPE)
          {
            running = false;
          }
        }
      }
      else
      {
        if(e.type == SDL_MOUSEMOTION)
        {
          window_mouse_x = e.motion.x;
          window_mouse_y = e.motion.y;
        }
        else if(e.type == SDL_KEYUP || e.type == SDL_KEYDOWN)
        {
          const bool down = e.type == SDL_KEYDOWN;
          const auto key  = ToKey(e.key.keysym);
          input.SetKeyState(key, down ? 1.0f : 0.0f);
        }
        else if(e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_MOUSEBUTTONUP)
        {
          const bool down = e.type == SDL_MOUSEBUTTONDOWN;
          window_mouse_x  = e.button.x;
          window_mouse_y  = e.button.y;
          if(e.button.button == SDL_BUTTON_LEFT)
          {
            mouse_lmb_down = down;
          }
        }
        else if(e.type == SDL_TEXTINPUT)
        {
          const std::string& input = e.text.text;
        }
      }
    }

    if(has_crashed == false)
    {
      integration.BindKeys(&duk, input);
    }

    if(has_crashed)
    {
      // todo: fix crash rendering, perhaps by using a debug gui or imgui
      // nothing much is required just a better overflow detection
      // when rendering the error, perhaps making the error more visible
      // though clicking around and debugging might be useful...
      init.ClearScreen(Color::CornflowerBlue);

      if(BeginFixedOverlay(ImguiCorner::Center, "Crashed"))
      {
        ImGui::TextDisabled("%s", crash_message_string.c_str());
        /*ImGui::InputTextMultiline(
            "##source",
            crash_message_string.c_str(),
            crash_message_string.length(),
            ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16),
            ImGuiInputTextFlags_ReadOnly); */
        if(ImGui::Button("Quit"))
        {
          running = false;
        }
        ImGui::End();
      }
    }
    else
    {
      init.ClearScreen(Color::DarkslateGray);
      world.Draw(&renderer);
    }

    imgui.Render();
    SDL_GL_SwapWindow(window);

    world.reg.RemoveRemoved();
  }

  SDL_DestroyWindow(window);
  SDL_Quit();
  return 0;
}
<|endoftext|>


<commit_before>// eval.cpp

#include "runtime.h"
#include "process.h"

// Includes needed for platform/OS interface

#include <stdio.h>
#include <string.h>

#ifdef _WIN32

#include <Windows.h>

#else

// TODO: These are currently the right ones for MacOS

#include <dirent.h>
#include <sys/types.h>
#include <unistd.h>
#include <libproc.h>
#include <mach-o/dyld.h>
#include <dlfcn.h>

#endif

namespace cog
{

	//

#if 0

	enum
	{
		kMaxArgs = 64,
	};

	struct ProcessSpawner
	{
		char const* executablePath = nullptr;
		char* args[kMaxArgs];
		int argCount = 0;

		ProcessSpawner(char const* appName)
		{
			addArg(appName);
		}

		ProcessSpawner(char const* appName, char const* executablePath)
			: executablePath(executablePath)
		{
			addArg(appName);
		}

		void addArg(char const* arg)
		{
			args[argCount++] = (char*)arg;
		}

		int spawnAndWait();
	};

#endif

	//

	typedef int(*DynamicFunc)();

	//

#if _WIN32

	// Try to find VS install path

	String tryToFindVisualStudioPath()
	{
		static const struct RegistryKeyInfo
		{
			char const* key;

		} kRegistryKeys[] =
		{
			{ "SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VC7", },
		};
		static const int kRegistryKeyCount = sizeof(kRegistryKeys) / sizeof(kRegistryKeys[0]);

		static const struct VersionInfo
		{
			char const* version;
		} kVersions[]
		{
			{ "15.0" },
			{ "14.0" },
			{ "12.0" },
			{ "11.0" },
			{ "10.0" },
			{ "9.0" },
			{ "8.0" },
		};
		static const int kVersionCount = sizeof(kVersions) / sizeof(kVersions[0]);

		char pathValue[MAX_PATH];
		DWORD pathSize = MAX_PATH;

		for (int ii = 0; ii < kRegistryKeyCount; ++ii)
		for (int jj = 0; jj < kVersionCount; ++jj)
		{
			auto& keyInfo = kRegistryKeys[ii];
			auto& versionInfo = kVersions[jj];

			HKEY registryKeyHandle;
			LONG keyResult = RegOpenKeyExA(
				HKEY_LOCAL_MACHINE,
				keyInfo.key,
				0,
				KEY_READ | KEY_WOW64_32KEY,
				&registryKeyHandle);

			LONG versionResult = RegQueryValueExA(
				registryKeyHandle,
				versionInfo.version,
				nullptr,
				nullptr,
				(LPBYTE)pathValue,
				&pathSize);
			if (versionResult == ERROR_SUCCESS)
			{
				// We found it!
				RegCloseKey(registryKeyHandle);

				return TerminatedStringSpan(pathValue);
			}

			RegCloseKey(registryKeyHandle);
		}
	}

#if 0
	int ProcessSpawner::spawnAndWait()
	{
		args[argCount] = nullptr;

		char commandLine[16384];
		char* cursor = commandLine;
		for (int aa = 0; aa < argCount; ++aa)
		{
			cursor += sprintf(cursor, "%s ", args[aa]);
		}

		PROCESS_INFORMATION processInfo;
		ZeroMemory(&processInfo, sizeof(processInfo));

		STARTUPINFOA startupInfo;
		ZeroMemory(&startupInfo, sizeof(startupInfo));
		startupInfo.cb = sizeof(startupInfo);

		CreateProcessA(
			executablePath ? executablePath : nullptr,
			commandLine,
			nullptr,
			nullptr,
			true,
			0,
			nullptr,
			nullptr,
			&startupInfo,
			&processInfo);

		WaitForSingleObject(processInfo.hProcess, INFINITE);

		CloseHandle(processInfo.hProcess);
		CloseHandle(processInfo.hThread);

		return 0;
	}
#endif

	void loadAndEval(char const* path)
	{
		String visualStudioPath = tryToFindVisualStudioPath();
		if (!visualStudioPath.asSpan().getLength())
			return;

		String executablePath;
		executablePath.append(visualStudioPath);
		executablePath.append("bin/cl.exe");

		String vcIncludePath;
		vcIncludePath.append("\"");
		vcIncludePath.append(visualStudioPath);
		vcIncludePath.append("include");
		vcIncludePath.append("\"");

		String vcLibPath;
		vcLibPath.append("/LIBPATH:\"");
		vcLibPath.append(visualStudioPath);
		vcLibPath.append("lib");
		vcLibPath.append("\"");

		char const* dynamicLibraryPath = "cog-eval.dll";

		ProcessSpawner compilerSpawner("cl", executablePath.asSpan().begin);

		compilerSpawner.addArg("/I");
		compilerSpawner.addArg(".");

		compilerSpawner.addArg("/I");
		compilerSpawner.addArg("source");

		compilerSpawner.addArg("/I");
		compilerSpawner.addArg(vcIncludePath.asSpan().begin);

		compilerSpawner.addArg("/I");
		compilerSpawner.addArg("\"C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.14393.0\\ucrt\"");

		compilerSpawner.addArg(path);

		compilerSpawner.addArg("/link");

		compilerSpawner.addArg(vcLibPath.asSpan().begin);

		compilerSpawner.addArg("/LIBPATH:\"C:\\Program Files (x86)\\Windows Kits\\10\\Lib\\10.0.14393.0\\ucrt\\x86\"");
		compilerSpawner.addArg("/LIBPATH:\"C:\\Program Files (x86)\\Windows Kits\\10\\Lib\\10.0.14393.0\\um\\x86\"");

		compilerSpawner.addArg("/DLL");

		String outArg;
		outArg.append("/OUT:");
		outArg.append(dynamicLibraryPath);
		compilerSpawner.addArg(outArg.asSpan().begin);

		int err = compilerSpawner.spawnAndWait();

		fprintf(stderr, "%s",
			compilerSpawner.stdoutText.asSpan().begin);

		if (err)
			return;

		auto dynamicLibraryHandle = LoadLibraryA(dynamicLibraryPath);

		DynamicFunc func = (DynamicFunc)GetProcAddress(dynamicLibraryHandle, "_cogc_eval");

		func();

		FreeLibrary(dynamicLibraryHandle);
	}

#else
	int ProcessSpawner::spawnAndWait()
	{
		args[argCount] = nullptr;

		pid_t childProcessID = fork();

		if (childProcessID == 0)
		{
			// We are the child process
			execvp(args[0], args);

			// Failed to `exec`!
			fprintf(stderr, "`execvp` failed\n");
			exit(1);
		}
		else
		{
			int childStatus = 0;
			for (;;)
			{
				pid_t terminatedProcessID = wait(&childStatus);
				if (terminatedProcessID == childProcessID)
				{
					return childStatus;
				}

				// ?
			}
		}
	}

	void loadAndEval(char const* path)
	{
		char const* dynamicLibraryPath = "cog-eval.so";

		ProcessSpawner compilerSpawner("clang++");

		compilerSpawner.addArg("-shared");
		compilerSpawner.addArg("-o");
		compilerSpawner.addArg(dynamicLibraryPath);

		compilerSpawner.addArg("-I");
		compilerSpawner.addArg(".");

		compilerSpawner.addArg("-I");
		compilerSpawner.addArg("source");

		compilerSpawner.addArg("-std=c++11");
		compilerSpawner.addArg("-Wno-writable-strings");
		compilerSpawner.addArg("-g");

		compilerSpawner.addArg(path);

		compilerSpawner.spawnAndWait();

		void* dynamicLibraryHandle = dlopen(dynamicLibraryPath, 0);

		void* symbol = dlsym(dynamicLibraryHandle, "_cogc_eval");

		DynamicFunc func = (DynamicFunc)symbol;

		func();

		dlclose(dynamicLibraryHandle);
	}

#endif

// Putting thesehere for lack of a better place

void print(char const* val)
{
	fprintf(stdout, "%s", val);
}

void print(String val)
{
	fprintf(stdout, "%s", val.asSpan().begin);
}

void print(Int val)
{
	fprintf(stdout, "%lld", val);
}

void print(UInt val)
{
	fprintf(stdout, "%llu", val);
}

} // cog
<commit_msg>Some fixes for eval/print logic<commit_after>// eval.cpp

#include "runtime.h"
#include "process.h"

// Includes needed for platform/OS interface

#include <stdio.h>
#include <string.h>

#ifdef _WIN32

#include <Windows.h>

#else

// TODO: These are currently the right ones for MacOS

#include <dirent.h>
#include <sys/types.h>
#include <unistd.h>
#include <libproc.h>
#include <mach-o/dyld.h>
#include <dlfcn.h>

#endif

namespace cog
{

	//

#if 0

	enum
	{
		kMaxArgs = 64,
	};

	struct ProcessSpawner
	{
		char const* executablePath = nullptr;
		char* args[kMaxArgs];
		int argCount = 0;

		ProcessSpawner(char const* appName)
		{
			addArg(appName);
		}

		ProcessSpawner(char const* appName, char const* executablePath)
			: executablePath(executablePath)
		{
			addArg(appName);
		}

		void addArg(char const* arg)
		{
			args[argCount++] = (char*)arg;
		}

		int spawnAndWait();
	};

#endif

	//

	typedef int(*DynamicFunc)();

	//

#if _WIN32

	// Try to find VS install path

	String tryToFindVisualStudioPath()
	{
		static const struct RegistryKeyInfo
		{
			char const* key;

		} kRegistryKeys[] =
		{
			{ "SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VC7", },
		};
		static const int kRegistryKeyCount = sizeof(kRegistryKeys) / sizeof(kRegistryKeys[0]);

		static const struct VersionInfo
		{
			char const* version;
		} kVersions[]
		{
			{ "15.0" },
			{ "14.0" },
			{ "12.0" },
			{ "11.0" },
			{ "10.0" },
			{ "9.0" },
			{ "8.0" },
		};
		static const int kVersionCount = sizeof(kVersions) / sizeof(kVersions[0]);

		char pathValue[MAX_PATH];
		DWORD pathSize = MAX_PATH;

		for (int ii = 0; ii < kRegistryKeyCount; ++ii)
		for (int jj = 0; jj < kVersionCount; ++jj)
		{
			auto& keyInfo = kRegistryKeys[ii];
			auto& versionInfo = kVersions[jj];

			HKEY registryKeyHandle;
			LONG keyResult = RegOpenKeyExA(
				HKEY_LOCAL_MACHINE,
				keyInfo.key,
				0,
				KEY_READ | KEY_WOW64_32KEY,
				&registryKeyHandle);

			LONG versionResult = RegQueryValueExA(
				registryKeyHandle,
				versionInfo.version,
				nullptr,
				nullptr,
				(LPBYTE)pathValue,
				&pathSize);
			if (versionResult == ERROR_SUCCESS)
			{
				// We found it!
				RegCloseKey(registryKeyHandle);

				return TerminatedStringSpan(pathValue);
			}

			RegCloseKey(registryKeyHandle);
		}
	}

#if 0
	int ProcessSpawner::spawnAndWait()
	{
		args[argCount] = nullptr;

		char commandLine[16384];
		char* cursor = commandLine;
		for (int aa = 0; aa < argCount; ++aa)
		{
			cursor += sprintf(cursor, "%s ", args[aa]);
		}

		PROCESS_INFORMATION processInfo;
		ZeroMemory(&processInfo, sizeof(processInfo));

		STARTUPINFOA startupInfo;
		ZeroMemory(&startupInfo, sizeof(startupInfo));
		startupInfo.cb = sizeof(startupInfo);

		CreateProcessA(
			executablePath ? executablePath : nullptr,
			commandLine,
			nullptr,
			nullptr,
			true,
			0,
			nullptr,
			nullptr,
			&startupInfo,
			&processInfo);

		WaitForSingleObject(processInfo.hProcess, INFINITE);

		CloseHandle(processInfo.hProcess);
		CloseHandle(processInfo.hThread);

		return 0;
	}
#endif

	void loadAndEval(char const* path)
	{
		String visualStudioPath = tryToFindVisualStudioPath();
		if (!visualStudioPath.asSpan().getLength())
			return;

		String executablePath;
		executablePath.append(visualStudioPath);
		executablePath.append("bin/cl.exe");

		String vcIncludePath;
		vcIncludePath.append("\"");
		vcIncludePath.append(visualStudioPath);
		vcIncludePath.append("include");
		vcIncludePath.append("\"");

		String vcLibPath;
		vcLibPath.append("/LIBPATH:\"");
		vcLibPath.append(visualStudioPath);
		vcLibPath.append("lib");
		vcLibPath.append("\"");

		char const* dynamicLibraryPath = "cog-eval.dll";

		ProcessSpawner compilerSpawner("cl", executablePath.asSpan().begin);

		compilerSpawner.addArg("/GS");
		compilerSpawner.addArg("/MDd");

		compilerSpawner.addArg("/I");
		compilerSpawner.addArg(".");

		compilerSpawner.addArg("/I");
		compilerSpawner.addArg("source");

		compilerSpawner.addArg("/I");
		compilerSpawner.addArg(vcIncludePath.asSpan().begin);

		compilerSpawner.addArg("/I");
		compilerSpawner.addArg("\"C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.14393.0\\ucrt\"");

		compilerSpawner.addArg(path);

		compilerSpawner.addArg("/link");

		compilerSpawner.addArg(vcLibPath.asSpan().begin);

		compilerSpawner.addArg("/LIBPATH:\"C:\\Program Files (x86)\\Windows Kits\\10\\Lib\\10.0.14393.0\\ucrt\\x86\"");
		compilerSpawner.addArg("/LIBPATH:\"C:\\Program Files (x86)\\Windows Kits\\10\\Lib\\10.0.14393.0\\um\\x86\"");

		compilerSpawner.addArg("/LIBPATH:.\\bin\\windows-x86\\Debug\\");
		compilerSpawner.addArg("runtime.lib");

		compilerSpawner.addArg("advapi32.lib");

		compilerSpawner.addArg("/DLL");
		compilerSpawner.addArg("/debug");

		String outArg;
		outArg.append("/OUT:");
		outArg.append(dynamicLibraryPath);
		compilerSpawner.addArg(outArg.asSpan().begin);

		int err = compilerSpawner.spawnAndWait();

//		fprintf(stderr, "%s",
//			compilerSpawner.stdoutText.asSpan().begin);

		if (err)
			return;

		auto dynamicLibraryHandle = LoadLibraryA(dynamicLibraryPath);

		DynamicFunc func = (DynamicFunc)GetProcAddress(dynamicLibraryHandle, "_cogc_eval");

		func();

		FreeLibrary(dynamicLibraryHandle);
	}

#else
	int ProcessSpawner::spawnAndWait()
	{
		args[argCount] = nullptr;

		pid_t childProcessID = fork();

		if (childProcessID == 0)
		{
			// We are the child process
			execvp(args[0], args);

			// Failed to `exec`!
			fprintf(stderr, "`execvp` failed\n");
			exit(1);
		}
		else
		{
			int childStatus = 0;
			for (;;)
			{
				pid_t terminatedProcessID = wait(&childStatus);
				if (terminatedProcessID == childProcessID)
				{
					return childStatus;
				}

				// ?
			}
		}
	}

	void loadAndEval(char const* path)
	{
		char const* dynamicLibraryPath = "cog-eval.so";

		ProcessSpawner compilerSpawner("clang++");

		compilerSpawner.addArg("-shared");
		compilerSpawner.addArg("-o");
		compilerSpawner.addArg(dynamicLibraryPath);

		compilerSpawner.addArg("-I");
		compilerSpawner.addArg(".");

		compilerSpawner.addArg("-I");
		compilerSpawner.addArg("source");

		compilerSpawner.addArg("-std=c++11");
		compilerSpawner.addArg("-Wno-writable-strings");
		compilerSpawner.addArg("-g");

		compilerSpawner.addArg(path);

		compilerSpawner.spawnAndWait();

		void* dynamicLibraryHandle = dlopen(dynamicLibraryPath, 0);

		void* symbol = dlsym(dynamicLibraryHandle, "_cogc_eval");

		DynamicFunc func = (DynamicFunc)symbol;

		func();

		dlclose(dynamicLibraryHandle);
	}

#endif

// Putting thesehere for lack of a better place

void print(char const* val)
{
	fprintf(stdout, "%s", val);
}

void print(String val)
{
	fprintf(stdout, "%s", val.asSpan().begin);
}

void print(Int val)
{
	fprintf(stdout, "%lld", (long long) val);
}

void print(UInt val)
{
	fprintf(stdout, "%llu", (unsigned long long) val);
}

} // cog
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <vexcl/vexcl.hpp>

#include <boost/compute.hpp>

#include <algorithm>
#include <QtGui>
#include <QtOpenGL>
#include <boost/compute/command_queue.hpp>
#include <boost/compute/kernel.hpp>
#include <boost/compute/program.hpp>
#include <boost/compute/source.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/interop/opengl.hpp>

using namespace std;
namespace compute = boost::compute;

int main (int argc, char* argv[])
{
	//set some default values for when no commandline arguments are given
	int accuracy = 90;
	int polygons = 50;
	int vertices = 6;
    //read input commandline arguments
    for (int i = 1; i < argc; ++i)
    {
        if (std::string(argv[i]) == "-a")
            {
                //initialise desired accuracy variable according to commandline argument -a
                accuracy = ;

            }
        if (std::string(argv[i]) == "-p")
            {
                //initialise maximum polygons variable according to commandline argument -p
                polygons = ;

            }
        if (std::string(argv[i]) == "-v")
            {
                //initialise maximum verices per polygon variable according to commandline argument -v
                vertices = ;

            }
    }
     // get the default compute device
    compute::device gpu = compute::system::default_device();

    // create a compute context and command queue
    compute::context ctx(gpu);
    compute::command_queue queue(ctx, gpu);

    //initialise variables in gpu
    const size_t n = 1024 * 1024;
    std::vector<double> leaderDNA(ctx, n);
    std::vector<double> mutatedDNA(ctx, n);
    std::vector<double> leaderDNArender(ctx, n);
    std::vector<double> mutatedDNArender(ctx, n);
    std::vector<double> originalimage(ctx, n);

    //load image into gpu memory
    // copy data to the device
    compute::copy(
        host_vector.begin(),
        host_vector.end(),
        device_vector.begin(),
        queue
    );

    //initialise variables
	class DNA
	{
		public:
		string genome;
        int polygons;
        int vertices;
        polygon[polygons];

	}
    class polygon;
    {
        public:
        int x[vertices];
        int y[vertices];
        int R;
        int G;
        int B;
        int alpha;
    }

    //initialise DNA with a random seed
    leaderDNA = seedDNA();
    //run render loop until desired accuracy is reached
    while (leaderaccuracy<accuracy)
        {
            //mutate from the leaderDNA
            mutatedDNA = mutateDNA(leaderDNA)
            //compute fitness of mutation vs leaderDNA
            //check if it is fitter, if so overwrite leaderDNA
            if (computefitness(leaderDNA,mutatedDNA) == 1)
            {
                //overwrite leaderDNA
                leaderDNA = mutatedDNA;
            }
            //compute accuracy percent
            computefitnesspercent(leaderDNA, originalimage)
        }
    //perform final render, output svg and raster image
    saverender(leaderDNA);
}
int computefitnesspercent (DNA, originalimage)
{
    //compute what % match DNA is to original image
}
int computefitness (DNA0, DNA1)
{
	//compute the fitness of input DNA, i.e. how close is it to original image?
  boost::compute::function<int (int)> computefitness =
    boost::compute::make_function_from_source<int (int)>(
        "computefitness",
        "int computefitness(int x) { //read leader dna

    //compare input dna to leader dna to find changed polygons
    compareDNA(leaderDNA,DNA);
    //create bounding box containing changed polygons

    //render leader dna within bounding box
    leaderrender = renderDNA(leaderDNA,boundx,boundy);
    //render input dna within bounding box
    inputrender = renderDNA(DNA,boundx,boundy);
    //compare leader and input dna rendered bounding boxes
    compareimage(leaderrender,inputrender);
    //returns 1 if dna1 is fitter than dna0, else returns 0 }"
    );

}
int seedDNA()
{
    //create a random seed dna
       //create random leader dna
    // generate random dna vector on the host
    std::vector<float> host_vector(1000000);
    std::generate(host_vector.begin(), host_vector.end(), rand);

    // create vector on the device
    compute::vector<float> device_vector(1000000, ctx);

    // copy data to the device
    compute::copy(
        host_vector.begin(),
        host_vector.end(),
        device_vector.begin(),
        queue
    );

}
int compareDNA(DNA0,DNA1)
{
    //compare DNA0 to DNA1 to find changed polygons
    boost::compute::function<int (int)> compareDNA =
    boost::compute::make_function_from_source<int (int)>(
        "compareDNA",
        "int compareDNA(int x) { return x + 4; }"
    );
}
int compareimage(image0,image1)
{
    //compare two raster images, return 1 if image1 fitter than image0, else return 0
    char *img1data, *img2data, fname[15];
    int s, n = 0, y = 0;

    sprintf(fname, "photo%d.bmp", p - 1);
    cout << "\n" << fname;
    ifstream img1(fname, ios::in|ios::binary|ios::ate);
    sprintf(fname, "photo%d.bmp", p);
    cout << "\n" << fname;
    ifstream img2(fname, ios::in|ios::binary|ios::ate);

    if (img1.is_open() && img2.is_open())
    {
        s = (int)img1.tellg();
        img1data = new char [s];
        img1.seekg (0, ios::beg);
        img1.read (img1data, s);
        img1.close();

        img2data = new char [s];
        img2.seekg (0, ios::beg);
        img2.read (img2data, s);
        img2.close();
    }

    for(int i=0; i<s; i++)
        if (img1data[i]==img2data[i]) y++;

    return (y);
}

int renderDNA (DNA, boundx0, boundy0, boundx1, boundy1)
{
	//render input DNA to a raster image
 boost::compute::function<int (int)> renderDNA =
    boost::compute::make_function_from_source<int (int)>(
        "renderDNA",
        "int renderDNA(int x) { //for each shape in dna
    {
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, gl_texture_);

    glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex2f(0, 0);
    glTexCoord2f(0, 1); glVertex2f(0, h);
    glTexCoord2f(1, 1); glVertex2f(w, h);
    glTexCoord2f(1, 0); glVertex2f(w, 0);
    glEnd();
    } }"
    );
}

int renderSVG (DNA, boundx0, boundy0, boundx1, boundy1)
{
    //render input DNA to a vector image
 boost::compute::function<int (int)> renderSVG =
    boost::compute::make_function_from_source<int (int)>(
        "renderSVG",
        "int renderSVG(int x) { //for each shape in dna
    {

    } }"
    );
}

}

int mutateDNA (DNA)
{
     //mutate dna
    boost::compute::function<int (int)> mutateDNA =
    boost::compute::make_function_from_source<int (int)>(
        "mutateDNA",
        "int mutateDNA(int DNA) { //mutate input DNA randomly
        mutated_shape = RANDINT(NUM_SHAPES);
    double roulette = RANDDOUBLE(2.8);
    double drastic = RANDDOUBLE(2);

    // mutate color
    if(roulette<1)
    {
        if(dna_test[mutated_shape].a < 0.01 // completely transparent shapes are stupid
                || roulette<0.25)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].a += RANDDOUBLE(0.1);
                dna_test[mutated_shape].a = CLAMP(dna_test[mutated_shape].a, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].a = RANDDOUBLE(1.0);
        }
        else if(roulette<0.50)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].r += RANDDOUBLE(0.1);
                dna_test[mutated_shape].r = CLAMP(dna_test[mutated_shape].r, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].r = RANDDOUBLE(1.0);
        }
        else if(roulette<0.75)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].g += RANDDOUBLE(0.1);
                dna_test[mutated_shape].g = CLAMP(dna_test[mutated_shape].g, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].g = RANDDOUBLE(1.0);
        }
        else
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].b += RANDDOUBLE(0.1);
                dna_test[mutated_shape].b = CLAMP(dna_test[mutated_shape].b, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].b = RANDDOUBLE(1.0);
        }
    }

    // mutate shape
    else if(roulette < 2.0)
    {
        int point_i = RANDINT(NUM_POINTS);
        if(roulette<1.5)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].points[point_i].x += (int)RANDDOUBLE(WIDTH/10.0);
                dna_test[mutated_shape].points[point_i].x = CLAMP(dna_test[mutated_shape].points[point_i].x, 0, WIDTH-1);
            }
            else
                dna_test[mutated_shape].points[point_i].x = RANDDOUBLE(WIDTH);
        }
        else
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].points[point_i].y += (int)RANDDOUBLE(HEIGHT/10.0);
                dna_test[mutated_shape].points[point_i].y = CLAMP(dna_test[mutated_shape].points[point_i].y, 0, HEIGHT-1);
            }
            else
                dna_test[mutated_shape].points[point_i].y = RANDDOUBLE(HEIGHT);
        }
    }

    // mutate stacking
    else
    {
        int destination = RANDINT(NUM_SHAPES);
        shape_t s = dna_test[mutated_shape];
        dna_test[mutated_shape] = dna_test[destination];
        dna_test[destination] = s;
        return destination;
    }
    return -1;
 }"
    );

}

int saveDNA(DNA)
{
	int result;

	while(1)
	{
		// start by writing a temp file.

		pFile = fopen ("volution.dna.temp","w");
		fprintf (pFile, DNA);
		fclose (pFile);

		// Then rename the real backup to a secondary backup.

		result = rename("volution.dna","volution_2.dna");

		// Then rename the temp file to the primary backup

		result = rename("volution.dna.temp","volution.dna");

		// Then delete the temp file

		result = remove("volution.dna.temp");

	}
}

int saverender(DNA)
{
    //render DNA and save resulting image to disk as .svg file and raster image (.png)

    //render image from DNA
    renderDNA(DNA);
    //save resultant image to disk as svg and png files
}

int importimage(image)
{
    //import specified image into the gpu memory
    // Load input image from file and load it into
    // an OpenCL image object
    int width, height;
    imageObjects[0] = LoadImage(context, argv[1], width, height);
    if (imageObjects[0] == 0)
    {
        std::cerr << "Error loading: " << std::string(argv[1]) << std::endl;
        Cleanup(context, commandQueue, program, kernel, imageObjects, sampler);
        return 1;
    }
     //load image into gpu memory
    // copy data to the device
    compute::copy(
        host_vector.begin(),
        host_vector.end(),
        device_vector.begin(),
        queue
    );
}

int drawshape()
{
	//user draws shape from ui

    //start drawing shape vertex by vertex
    //until max number of vertices reached or user closes polygon by clicking on initial vertex

    //check if drawn shape gives a better fitness

    //if it does update the leaderDNA
}

int dragvertex()
{
	//user drags vertex from ui

    //user stops dragging vertex

    //check if dragged vertex improves fitness

    //if it does update the leaderDNA
}
<commit_msg>tidying<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <vexcl/vexcl.hpp>

#include <boost/compute.hpp>

#include <algorithm>
#include <QtGui>
#include <QtOpenGL>
#include <boost/compute/command_queue.hpp>
#include <boost/compute/kernel.hpp>
#include <boost/compute/program.hpp>
#include <boost/compute/source.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/interop/opengl.hpp>

using namespace std;
namespace compute = boost::compute;

int main (int argc, char* argv[])
{
	//set some default values for when no commandline arguments are given
	int accuracy = 90;
	int polygons = 50;
	int vertices = 6;
    //read input commandline arguments
    for (int i = 1; i < argc; ++i)
    {
        if (std::string(argv[i]) == "-a")
            {
                //initialise desired accuracy variable according to commandline argument -a
                accuracy = ;

            }
        if (std::string(argv[i]) == "-p")
            {
                //initialise maximum polygons variable according to commandline argument -p
                polygons = ;

            }
        if (std::string(argv[i]) == "-v")
            {
                //initialise maximum verices per polygon variable according to commandline argument -v
                vertices = ;

            }
    }
     // get the default compute device
    compute::device gpu = compute::system::default_device();

    // create a compute context and command queue
    compute::context ctx(gpu);
    compute::command_queue queue(ctx, gpu);

    //initialise variables in gpu
    const size_t n = 1024 * 1024;
    std::vector<double> leaderDNA(ctx, n);
    std::vector<double> mutatedDNA(ctx, n);
    std::vector<double> leaderDNArender(ctx, n);
    std::vector<double> mutatedDNArender(ctx, n);
    std::vector<double> originalimage(ctx, n);

    //load image into gpu memory
    if (std::string(argv[i]) == "")
            {
                //load file according to commandline argument into gpu vector
                std::vector<double> leaderDNA(ctx, n);
            }
    // copy data to the device
    compute::copy(
        host_vector.begin(),
        host_vector.end(),
        device_vector.begin(),
        queue
    );

    //initialise variables
	class DNA
	{
		public:
		string genome;
        int polygons;
        int vertices;
        polygon[polygons];

	}
    class polygon;
    {
        public:
        int x[vertices];
        int y[vertices];
        int R;
        int G;
        int B;
        int alpha;
    }

    //initialise DNA with a random seed
    leaderDNA = seedDNA();
    //run render loop until desired accuracy is reached
    while (leaderaccuracy<accuracy)
        {
            //mutate from the leaderDNA
            mutatedDNA = mutateDNA(leaderDNA)
            //compute fitness of mutation vs leaderDNA
            //check if it is fitter, if so overwrite leaderDNA
            if (computefitness(leaderDNA,mutatedDNA) == 1)
            {
                //overwrite leaderDNA
                leaderDNA = mutatedDNA;
            }
            //compute accuracy percent
            computefitnesspercent(leaderDNA, originalimage)
        }
    //perform final render, output svg and raster image
    saverender(leaderDNA);
}
int computefitnesspercent (DNA, originalimage)
{
    //compute what % match DNA is to original image
     boost::compute::function<int (int)> computefitnesspercent =
    boost::compute::make_function_from_source<int (int)>(
        "computefitnesspercent",
        "int computefitnesspercent(int x) { //read leader dna

    //compare input dna to leader dna to find changed polygons
    compareDNA(leaderDNA,DNA);
    //create bounding box containing changed polygons

    //render leader dna within bounding box
    leaderrender = renderDNA(leaderDNA,boundx,boundy);
    //render input dna within bounding box
    inputrender = renderDNA(DNA,boundx,boundy);
    //compare leader and input dna rendered bounding boxes
    compareimage(leaderrender,inputrender);
    //returns % match }"
    );
}
int computefitness (DNA0, DNA1)
{
	//compute the fitness of input DNA, i.e. how close is it to original image?
  boost::compute::function<int (int)> computefitness =
    boost::compute::make_function_from_source<int (int)>(
        "computefitness",
        "int computefitness(int x) { //read leader dna

    //compare input dna to leader dna to find changed polygons
    compareDNA(leaderDNA,DNA);
    //create bounding box containing changed polygons

    //render leader dna within bounding box
    leaderrender = renderDNA(leaderDNA,boundx,boundy);
    //render input dna within bounding box
    inputrender = renderDNA(DNA,boundx,boundy);
    //compare leader and input dna rendered bounding boxes
    compareimage(leaderrender,inputrender);
    //returns 1 if dna1 is fitter than dna0, else returns 0 }"
    );

}
int seedDNA()
{
    //create a random seed dna
       //create random leader dna
    // generate random dna vector on the host
    std::vector<float> host_vector(1000000);
    std::generate(host_vector.begin(), host_vector.end(), rand);

    // create vector on the device
    compute::vector<float> device_vector(1000000, ctx);

    // copy data to the device
    compute::copy(
        host_vector.begin(),
        host_vector.end(),
        device_vector.begin(),
        queue
    );

}
int compareDNA(DNA0,DNA1)
{
    //compare DNA0 to DNA1 to find changed polygons
    boost::compute::function<int (int)> compareDNA =
    boost::compute::make_function_from_source<int (int)>(
        "compareDNA",
        "int compareDNA(int x) { return x + 4; }"
    );
}
int compareimage(image0,image1)
{
    //compare two raster images, return 1 if image1 fitter than image0, else return 0
    boost::compute::function<int (int)> compareDNA =
    boost::compute::make_function_from_source<int (int)>(
        "compareimage",
        "int compareimage(int image0, int image1) { return x + 4; }"
    );
}

int renderDNA (DNA, boundx0, boundy0, boundx1, boundy1)
{
	//render input DNA to a raster image
 boost::compute::function<int (int)> renderDNA =
    boost::compute::make_function_from_source<int (int)>(
        "renderDNA",
        "int renderDNA(int x) { //for each shape in dna
    {
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, gl_texture_);

    glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex2f(0, 0);
    glTexCoord2f(0, 1); glVertex2f(0, h);
    glTexCoord2f(1, 1); glVertex2f(w, h);
    glTexCoord2f(1, 0); glVertex2f(w, 0);
    glEnd();
    } }"
    );
}

int renderSVG (DNA, boundx0, boundy0, boundx1, boundy1)
{
    //render input DNA to a vector image in an opengl texture
 boost::compute::function<int (int)> renderSVG =
    boost::compute::make_function_from_source<int (int)>(
        "renderSVG",
        "int renderSVG(int x) {

        //for each shape in dna
    {
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, gl_texture_);

    glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex2f(0, 0);
    glTexCoord2f(0, 1); glVertex2f(0, h);
    glTexCoord2f(1, 1); glVertex2f(w, h);
    glTexCoord2f(1, 0); glVertex2f(w, 0);
    glEnd();
    } }"
    );
}

}

int mutateDNA (DNA)
{
     //mutate dna
    boost::compute::function<int (int)> mutateDNA =
    boost::compute::make_function_from_source<int (int)>(
        "mutateDNA",
        "int mutateDNA(int DNA) { //mutate input DNA randomly
        mutated_shape = RANDINT(NUM_SHAPES);
    double roulette = RANDDOUBLE(2.8);
    double drastic = RANDDOUBLE(2);

    // mutate color
    if(roulette<1)
    {
        if(dna_test[mutated_shape].a < 0.01 // completely transparent shapes are stupid
                || roulette<0.25)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].a += RANDDOUBLE(0.1);
                dna_test[mutated_shape].a = CLAMP(dna_test[mutated_shape].a, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].a = RANDDOUBLE(1.0);
        }
        else if(roulette<0.50)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].r += RANDDOUBLE(0.1);
                dna_test[mutated_shape].r = CLAMP(dna_test[mutated_shape].r, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].r = RANDDOUBLE(1.0);
        }
        else if(roulette<0.75)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].g += RANDDOUBLE(0.1);
                dna_test[mutated_shape].g = CLAMP(dna_test[mutated_shape].g, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].g = RANDDOUBLE(1.0);
        }
        else
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].b += RANDDOUBLE(0.1);
                dna_test[mutated_shape].b = CLAMP(dna_test[mutated_shape].b, 0.0, 1.0);
            }
            else
                dna_test[mutated_shape].b = RANDDOUBLE(1.0);
        }
    }

    // mutate shape
    else if(roulette < 2.0)
    {
        int point_i = RANDINT(NUM_POINTS);
        if(roulette<1.5)
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].points[point_i].x += (int)RANDDOUBLE(WIDTH/10.0);
                dna_test[mutated_shape].points[point_i].x = CLAMP(dna_test[mutated_shape].points[point_i].x, 0, WIDTH-1);
            }
            else
                dna_test[mutated_shape].points[point_i].x = RANDDOUBLE(WIDTH);
        }
        else
        {
            if(drastic < 1)
            {
                dna_test[mutated_shape].points[point_i].y += (int)RANDDOUBLE(HEIGHT/10.0);
                dna_test[mutated_shape].points[point_i].y = CLAMP(dna_test[mutated_shape].points[point_i].y, 0, HEIGHT-1);
            }
            else
                dna_test[mutated_shape].points[point_i].y = RANDDOUBLE(HEIGHT);
        }
    }

    // mutate stacking
    else
    {
        int destination = RANDINT(NUM_SHAPES);
        shape_t s = dna_test[mutated_shape];
        dna_test[mutated_shape] = dna_test[destination];
        dna_test[destination] = s;
        return destination;
    }
    return -1;
 }"
    );

}

int saveDNA(DNA)
{
	int result;

	while(1)
	{
		// start by writing a temp file.

		pFile = fopen ("volution.dna.temp","w");
		fprintf (pFile, DNA);
		fclose (pFile);

		// Then rename the real backup to a secondary backup.

		result = rename("volution.dna","volution_2.dna");

		// Then rename the temp file to the primary backup

		result = rename("volution.dna.temp","volution.dna");

		// Then delete the temp file

		result = remove("volution.dna.temp");

	}
}

int saverender(DNA)
{
    //render DNA and save resulting image to disk as .svg file and raster image (.png)

    //render image from DNA
    renderDNA(DNA);
    //save resultant image to disk as svg and png files
}

int importimage(image)
{
    //import specified image into the gpu memory
    // create vector on the device
    compute::vector<float> device_vector(1000000, ctx);
     //load image into gpu memory
    // copy data to the device
    compute::copy(
        host_vector.begin(),
        host_vector.end(),
        device_vector.begin(),
        queue
    );
}

int drawshape()
{
	//user draws shape from ui

    //start drawing shape vertex by vertex
    //until max number of vertices reached or user closes polygon by clicking on initial vertex

    //check if drawn shape gives a better fitness

    //if it does update the leaderDNA
}

int dragvertex()
{
	//user drags vertex from ui

    //user stops dragging vertex

    //check if dragged vertex improves fitness

    //if it does update the leaderDNA
}
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * @author Lefteris Karapetsas <lefteris@ethdev.com>
 * @date 2014
 * Unit tests for the solidity compiler JSON Interface output.
 */

#include <boost/test/unit_test.hpp>
#include <libsolidity/CompilerStack.h>
#include <jsonrpc/json/json.h>
#include <libdevcore/Exceptions.h>

namespace dev
{
namespace solidity
{
namespace test
{

class DocumentationChecker
{
public:
	void checkNatspec(std::string const& _code, std::string const& _expectedDocumentationString)
	{
		try
		{
			m_compilerStack.parse(_code);
		}
		catch (const std::exception& e)
		{
			std::string const* extra = boost::get_error_info<errinfo_comment>(e);
			std::string msg = std::string("Parsing contract failed with: ") +
				e.what() + std::string("\n");
			if (extra)
				msg += *extra;
			BOOST_FAIL(msg);
		}
		auto generatedDocumentationString = m_compilerStack.getDocumentation();
		Json::Value generatedDocumentation;
		m_reader.parse(generatedDocumentationString, generatedDocumentation);
		Json::Value expectedDocumentation;
		m_reader.parse(_expectedDocumentationString, expectedDocumentation);
		BOOST_CHECK_MESSAGE(expectedDocumentation == generatedDocumentation,
							"Expected " << _expectedDocumentationString <<
							"\n but got:\n" << generatedDocumentationString);
	}

private:
	CompilerStack m_compilerStack;
	Json::Reader m_reader;
};

BOOST_FIXTURE_TEST_SUITE(SolidityNatspecJSON, DocumentationChecker)

BOOST_AUTO_TEST_CASE(basic_test)
{
	char const* sourceCode = "contract test {\n"
	"  /// Multiplies `a` by 7\n"
	"  function mul(uint a) returns(uint d) { return a * 7; }\n"
	"}\n";

	char const* natspec = "{"
	"\"methods\":{"
	"    \"mul\":{ \"user\": \" Multiplies `a` by 7\"}"
	"}}";

	checkNatspec(sourceCode, natspec);
}

BOOST_AUTO_TEST_CASE(multiline_comment)
{
	char const* sourceCode = "contract test {\n"
	"  /// Multiplies `a` by 7\n"
	"  /// and then adds `b`\n"
	"  function mul_and_add(uint a, uint256 b) returns(uint256 d)\n"
	"  {\n"
	"      return (a * 7) + b;\n"
	"  }\n"
	"}\n";

	char const* natspec = "{"
	"\"methods\":{"
	"    \"mul_and_add\":{ \"user\": \" Multiplies `a` by 7\n and then adds `b`\"}"
	"}}";

	checkNatspec(sourceCode, natspec);
}

BOOST_AUTO_TEST_CASE(multiple_functions)
{
	char const* sourceCode = "contract test {\n"
	"  /// Multiplies `a` by 7\n"
	"  /// and then adds `b`\n"
	"  function mul_and_add(uint a, uint256 b) returns(uint256 d)\n"
	"  {\n"
	"      return (a * 7) + b;\n"
	"  }\n"
	"\n"
	"  /// Divides `input` by `div`\n"
	"  function divide(uint input, uint div) returns(uint d)\n"
	"  {\n"
	"      return input / div;\n"
	"  }\n"
	"  /// Subtracts 3 from `input`\n"
	"  function sub(int input) returns(int d)\n"
	"  {\n"
	"      return input - 3;\n"
	"  }\n"
	"}\n";

	char const* natspec = "{"
	"\"methods\":{"
	"    \"mul_and_add\":{ \"user\": \" Multiplies `a` by 7\n and then adds `b`\"},"
	"    \"divide\":{ \"user\": \" Divides `input` by `div`\"},"
	"    \"sub\":{ \"user\": \" Subtracts 3 from `input`\"}"
	"}}";

	checkNatspec(sourceCode, natspec);
}

BOOST_AUTO_TEST_CASE(empty_contract)
{
	char const* sourceCode = "contract test {\n"
	"}\n";

	char const* natspec = "{\"methods\":{} }";

	checkNatspec(sourceCode, natspec);
}

BOOST_AUTO_TEST_SUITE_END()

}
}
}
<commit_msg>Separate user and dev natspec documentation<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * @author Lefteris Karapetsas <lefteris@ethdev.com>
 * @date 2014
 * Unit tests for the solidity compiler JSON Interface output.
 */

#include <boost/test/unit_test.hpp>
#include <libsolidity/CompilerStack.h>
#include <jsonrpc/json/json.h>
#include <libdevcore/Exceptions.h>

namespace dev
{
namespace solidity
{
namespace test
{

class DocumentationChecker
{
public:
	void checkNatspec(std::string const& _code,
					  std::string const& _expectedDocumentationString,
					  bool _userDocumentation)
	{
		std::string generatedDocumentationString;
		try
		{
			m_compilerStack.parse(_code);
		}
		catch (const std::exception& e)
		{
			std::string const* extra = boost::get_error_info<errinfo_comment>(e);
			std::string msg = std::string("Parsing contract failed with: ") +
				e.what() + std::string("\n");
			if (extra)
				msg += *extra;
			BOOST_FAIL(msg);
		}

		if (_userDocumentation)
			generatedDocumentationString = m_compilerStack.getUserDocumentation();
		else
			generatedDocumentationString = m_compilerStack.getDevDocumentation();
		Json::Value generatedDocumentation;
		m_reader.parse(generatedDocumentationString, generatedDocumentation);
		Json::Value expectedDocumentation;
		m_reader.parse(_expectedDocumentationString, expectedDocumentation);
		BOOST_CHECK_MESSAGE(expectedDocumentation == generatedDocumentation,
							"Expected " << _expectedDocumentationString <<
							"\n but got:\n" << generatedDocumentationString);
	}

private:
	CompilerStack m_compilerStack;
	Json::Reader m_reader;
};

BOOST_FIXTURE_TEST_SUITE(SolidityNatspecJSON, DocumentationChecker)

BOOST_AUTO_TEST_CASE(user_basic_test)
{
	char const* sourceCode = "contract test {\n"
	"  /// Multiplies `a` by 7\n"
	"  function mul(uint a) returns(uint d) { return a * 7; }\n"
	"}\n";

	char const* natspec = "{"
	"\"methods\":{"
	"    \"mul\":{ \"notice\": \" Multiplies `a` by 7\"}"
	"}}";

	checkNatspec(sourceCode, natspec, true);
}

BOOST_AUTO_TEST_CASE(user_multiline_comment)
{
	char const* sourceCode = "contract test {\n"
	"  /// Multiplies `a` by 7\n"
	"  /// and then adds `b`\n"
	"  function mul_and_add(uint a, uint256 b) returns(uint256 d)\n"
	"  {\n"
	"      return (a * 7) + b;\n"
	"  }\n"
	"}\n";

	char const* natspec = "{"
	"\"methods\":{"
	"    \"mul_and_add\":{ \"notice\": \" Multiplies `a` by 7\n and then adds `b`\"}"
	"}}";

	checkNatspec(sourceCode, natspec, true);
}

BOOST_AUTO_TEST_CASE(user_multiple_functions)
{
	char const* sourceCode = "contract test {\n"
	"  /// Multiplies `a` by 7\n"
	"  /// and then adds `b`\n"
	"  function mul_and_add(uint a, uint256 b) returns(uint256 d)\n"
	"  {\n"
	"      return (a * 7) + b;\n"
	"  }\n"
	"\n"
	"  /// Divides `input` by `div`\n"
	"  function divide(uint input, uint div) returns(uint d)\n"
	"  {\n"
	"      return input / div;\n"
	"  }\n"
	"  /// Subtracts 3 from `input`\n"
	"  function sub(int input) returns(int d)\n"
	"  {\n"
	"      return input - 3;\n"
	"  }\n"
	"}\n";

	char const* natspec = "{"
	"\"methods\":{"
	"    \"mul_and_add\":{ \"notice\": \" Multiplies `a` by 7\n and then adds `b`\"},"
	"    \"divide\":{ \"notice\": \" Divides `input` by `div`\"},"
	"    \"sub\":{ \"notice\": \" Subtracts 3 from `input`\"}"
	"}}";

	checkNatspec(sourceCode, natspec, true);
}

BOOST_AUTO_TEST_CASE(user_empty_contract)
{
	char const* sourceCode = "contract test {\n"
	"}\n";

	char const* natspec = "{\"methods\":{} }";

	checkNatspec(sourceCode, natspec, true);
}

BOOST_AUTO_TEST_SUITE_END()

}
}
}
<|endoftext|>


<commit_before>/*
 * Author: Yevgeniy Kiveisha <yevgeniy.kiveisha@intel.com>
 * Copyright (c) 2014 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 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 <iostream>
#include <unistd.h>
#include <stdlib.h>

#include "ecs1030.h"

using namespace upm;

struct ECS1030Exception : public std::exception {
    std::string message;
    ECS1030Exception (std::string msg) : message (msg) { }
    ~ECS1030Exception () throw () { }
    const char* what() const throw () { return message.c_str(); }
};

ECS1030::ECS1030 (uint8_t pinNumber) {
    m_dataPinCtx = mraa_aio_init(pinNumber);
    if (m_dataPinCtx == NULL) {
        throw ECS1030Exception ("GPIO failed to initilize");
    }

    m_calibration = 111.1;
}

ECS1030::~ECS1030 () {
    mraa_result_t error = MRAA_SUCCESS;

    error = mraa_aio_close (m_dataPinCtx);
    if (error != MRAA_SUCCESS) {
    }
}

double
ECS1030::getCurrency_A () {
    int     sensorValue  = 0;
    float   rLoad        = 0;
    float   volt         = 0;
    float   rms          = 0;

    for (int i = 0; i < NUMBER_OF_SAMPLES; i++) {
        sensorValue = mraa_aio_read (m_dataPinCtx);
        volt = (VOLT_M * sensorValue) - 2.5;
        volt = volt * volt;
        rms = rms + volt;
        usleep (DELAY_MS);
    }

    rms = rms / (float)NUMBER_OF_SAMPLES;
    rms = sqrt(rms);
    return rms / R_LOAD;
}

double
ECS1030::getCurrency_B () {
    double sumCurrency    = 0;

    for (int i = 0; i < NUMBER_OF_SAMPLES; i++) {
        m_lastSample = m_sample;
        m_sample = mraa_aio_read (m_dataPinCtx);
        m_lastFilter = m_filteredSample;
        m_filteredSample = 0.996 * (m_lastFilter + m_sample - m_lastSample);
        sumCurrency += (m_filteredSample * m_filteredSample);
    }

    double ratio = m_calibration * ((SUPPLYVOLTAGE / 1000.0) / (ADC_RESOLUTION));
    return ( ratio * sqrt(sumCurrency / NUMBER_OF_SAMPLES) );
}

double
ECS1030::getPower_A () {
    return 220.0 * getCurrency_A ();
}

double
ECS1030::getPower_B () {
    return 220.0 * getCurrency_B ();
}
<commit_msg>ecs1030: remove custom exception and use a standard one<commit_after>/*
 * Author: Yevgeniy Kiveisha <yevgeniy.kiveisha@intel.com>
 * Copyright (c) 2014 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 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 <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <string>
#include <stdexcept>

#include "ecs1030.h"

using namespace upm;

ECS1030::ECS1030 (uint8_t pinNumber) {
    m_dataPinCtx = mraa_aio_init(pinNumber);
    if (m_dataPinCtx == NULL) {
      throw std::invalid_argument(std::string(__FUNCTION__) +
                                  ": mraa_aio_init() failed");
    }

    m_calibration = 111.1;
}

ECS1030::~ECS1030 () {
    mraa_result_t error = MRAA_SUCCESS;

    error = mraa_aio_close (m_dataPinCtx);
    if (error != MRAA_SUCCESS) {
    }
}

double
ECS1030::getCurrency_A () {
    int     sensorValue  = 0;
    float   rLoad        = 0;
    float   volt         = 0;
    float   rms          = 0;

    for (int i = 0; i < NUMBER_OF_SAMPLES; i++) {
        sensorValue = mraa_aio_read (m_dataPinCtx);
        volt = (VOLT_M * sensorValue) - 2.5;
        volt = volt * volt;
        rms = rms + volt;
        usleep (DELAY_MS);
    }

    rms = rms / (float)NUMBER_OF_SAMPLES;
    rms = sqrt(rms);
    return rms / R_LOAD;
}

double
ECS1030::getCurrency_B () {
    double sumCurrency    = 0;

    for (int i = 0; i < NUMBER_OF_SAMPLES; i++) {
        m_lastSample = m_sample;
        m_sample = mraa_aio_read (m_dataPinCtx);
        m_lastFilter = m_filteredSample;
        m_filteredSample = 0.996 * (m_lastFilter + m_sample - m_lastSample);
        sumCurrency += (m_filteredSample * m_filteredSample);
    }

    double ratio = m_calibration * ((SUPPLYVOLTAGE / 1000.0) / (ADC_RESOLUTION));
    return ( ratio * sqrt(sumCurrency / NUMBER_OF_SAMPLES) );
}

double
ECS1030::getPower_A () {
    return 220.0 * getCurrency_A ();
}

double
ECS1030::getPower_B () {
    return 220.0 * getCurrency_B ();
}
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*! @file
    @brief  input クラス @n
			数値、文字列などの入力クラス
			Copyright 2017 Kunihito Hiramatsu
    @author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <type_traits>

extern "C" {

	char sci_getch(void);

};

namespace utils {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  標準入力ファンクタ
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class def_chainp {
		const char* str_;
		char		last_;
		bool		unget_;
	public:
		def_chainp(const char* str = nullptr) : str_(str), last_(0), unget_(false) { }

		void unget() {
			unget_ = true;
		}

		char operator() () {
			if(unget_) {
				unget_ = false;
			} else {
				if(str_ == nullptr) {
					last_ = sci_getch();
				} else {
					last_ = *str_;
					if(last_ != 0) { ++str_; }
				}
			}
			return last_;
		}
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  汎用入力クラス
		@param[in]	INP	入力クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class INP>
	class basic_input {

		const char*	form_;

		INP			inp_;

		uint32_t bin_() {
			uint32_t a = 0;
			char ch;
			while((ch = inp_()) != 0 && ch >= '0' && ch <= '1') {
				a <<= 1;
				a += ch - '0';
			}
			return a;
		}

		uint32_t oct_() {
			uint32_t a = 0;
			char ch;
			while((ch = inp_()) != 0 && ch >= '0' && ch <= '7') {
				a <<= 3;
				a += ch - '0';
			}
			return a;
		}

		uint32_t dec_() {
			uint32_t a = 0;
			char ch;
			while((ch = inp_()) != 0 && ch >= '0' && ch <= '9') {
				a *= 10;
				a += ch - '0';
			}
			return a;
		}

		uint32_t hex_() {
			uint32_t a = 0;
			char ch;
			while((ch = inp_()) != 0) {
				if(ch >= '0' && ch <= '9') {
					a <<= 4;
					a += ch - '0';
				} else if(ch >= 'A' && ch <= 'F') {
					a <<= 4;
					a += ch - 'A' + 10;
				} else if(ch >= 'a' && ch <= 'f') {
					a <<= 4;
					a += ch - 'a' + 10;
				} else {
					break;
				}
			}
			return a;
		}

		enum class mode : uint8_t {
			NONE,
			BIN,
			OCT,
			DEC,
			HEX,
		};
		mode	mode_;
		bool	err_;

		int		num_;

		enum class fmm : uint8_t {
			none,
			type,

		};

		void next_()
		{
			fmm cm = fmm::none;
			char ch;
			while((ch = *form_++) != 0) {
				switch(cm) {
				case fmm::none:
					if(ch == '[') {
						auto a = inp_();
						const char* p = form_;
						bool ok = false;
						while((ch = *p++) != 0 && ch != ']') {
							if(ch == a) ok = true;
						}
						form_ = p;
						if(!ok) {
							err_ = true;
							return;
						}
					} else if(ch == '%' && *form_ != '%') {
						cm = fmm::type;
					} else if(ch != inp_()) {
						err_ = true;
						return;
					}
					break;
				case fmm::type:
					if(ch == 'b' || ch == 'B') {
						mode_ = mode::BIN;
					} else if(ch == 'o' || ch == 'O') {
						mode_ = mode::OCT;
					} else if(ch == 'd' || ch == 'D') {
						mode_ = mode::DEC;
					} else if(ch == 'x' || ch == 'X') {
						mode_ = mode::HEX;
					} else {
						err_ = true;
					}
					return;
				}
			}
			if(ch == 0 && inp_() == 0) ;
			else {
				err_ = true;
			}
		}

		int32_t nb_(bool sign = true)
		{
			bool neg = false;
			if(sign) {
				auto s = inp_();
				if(s == '-') { neg = true; }
				else if(s == '+') { neg = false; }
				else inp_.unget();
			}
			uint32_t v = 0;
			switch(mode_) {
			case mode::BIN:
				v = bin_();
				break;
			case mode::OCT:
				v = oct_();
				break;
			case mode::DEC:
				v = dec_();
				break;
			case mode::HEX:
				v = hex_();
				break;
			default:
				err_ = true;
				break;
			}
			if(!err_) {
				inp_.unget();
				next_();
				if(!err_) ++num_;
			}
			if(neg) return -static_cast<int32_t>(v);
			else return static_cast<int32_t>(v);
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
			@param[in]	form	入力形式
			@param[in]	inp		変換文字列（nullptrの場合、sci_getch で取得）
		*/
		//-----------------------------------------------------------------//
		basic_input(const char* form, const char* inp = nullptr) : form_(form), inp_(inp),
			mode_(mode::NONE), err_(false), num_(0)
		{
			next_();
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  正常変換数を取得
			@return 正常変換数
		*/
		//-----------------------------------------------------------------//
		int num() const { return num_; }

		//-----------------------------------------------------------------//
		/*!
			@brief  テンプレート・オペレーター「%」
			@param[in]	val	整数型
			@return	自分の参照
		*/
		//-----------------------------------------------------------------//
		template <typename T>
		basic_input& operator % (T& val)
		{
			if(err_) return *this;
			val = nb_(!std::is_signed<T>::value);
			return *this;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  オペレーター「=」
		*/
		//-----------------------------------------------------------------//
		basic_input& operator = (const basic_input& in) { return *this; }
	};

	typedef basic_input<def_chainp> input;

}
<commit_msg>update float<commit_after>#pragma once
//=====================================================================//
/*! @file
    @brief  input クラス @n
			数値、文字列などの入力クラス
			Copyright 2017 Kunihito Hiramatsu
    @author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <type_traits>

extern "C" {

	char sci_getch(void);

};

namespace utils {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  標準入力ファンクタ
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class def_chainp {
		const char* str_;
		char		last_;
		bool		unget_;
	public:
		def_chainp(const char* str = nullptr) : str_(str), last_(0), unget_(false) { }

		void unget() {
			unget_ = true;
		}

		char operator() () {
			if(unget_) {
				unget_ = false;
			} else {
				if(str_ == nullptr) {
					last_ = sci_getch();
				} else {
					last_ = *str_;
					if(last_ != 0) { ++str_; }
				}
			}
			return last_;
		}
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  汎用入力クラス
		@param[in]	INP	入力クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class INP>
	class basic_input {

		const char*	form_;

		INP			inp_;

		uint32_t bin_() {
			uint32_t a = 0;
			char ch;
			while((ch = inp_()) != 0 && ch >= '0' && ch <= '1') {
				a <<= 1;
				a += ch - '0';
			}
			return a;
		}

		uint32_t oct_() {
			uint32_t a = 0;
			char ch;
			while((ch = inp_()) != 0 && ch >= '0' && ch <= '7') {
				a <<= 3;
				a += ch - '0';
			}
			return a;
		}

		uint32_t dec_() {
			uint32_t a = 0;
			char ch;
			while((ch = inp_()) != 0 && ch >= '0' && ch <= '9') {
				a *= 10;
				a += ch - '0';
			}
			return a;
		}

		uint32_t hex_() {
			uint32_t a = 0;
			char ch;
			while((ch = inp_()) != 0) {
				if(ch >= '0' && ch <= '9') {
					a <<= 4;
					a += ch - '0';
				} else if(ch >= 'A' && ch <= 'F') {
					a <<= 4;
					a += ch - 'A' + 10;
				} else if(ch >= 'a' && ch <= 'f') {
					a <<= 4;
					a += ch - 'a' + 10;
				} else {
					break;
				}
			}
			return a;
		}

		float real_() {
			uint32_t a = 0;
			uint32_t b = 0;
			uint32_t c = 1;
			char ch;
			bool p = false;
			while((ch = inp_()) != 0) {
				if(ch >= '0' && ch <= '9') {
					a *= 10;
					a += ch - '0';
					c *= 10;
				} else if(ch == '.') {
					b = a;
					a = 0;
					c = 1;
					p = true;
				} else {
					break;
				}
			}
			if(p) {
				return static_cast<float>(b) + static_cast<float>(a) / static_cast<float>(c);
			} else {
				return static_cast<float>(a);
			}
		}

		enum class mode : uint8_t {
			NONE,
			BIN,
			OCT,
			DEC,
			HEX,
			FLOAT,
		};
		mode	mode_;
		bool	err_;

		int		num_;

		enum class fmm : uint8_t {
			none,
			type,

		};

		void next_()
		{
			fmm cm = fmm::none;
			char ch;
			while((ch = *form_++) != 0) {
				switch(cm) {
				case fmm::none:
					if(ch == '[') {
						auto a = inp_();
						const char* p = form_;
						bool ok = false;
						while((ch = *p++) != 0 && ch != ']') {
							if(ch == a) ok = true;
						}
						form_ = p;
						if(!ok) {
							err_ = true;
							return;
						}
					} else if(ch == '%' && *form_ != '%') {
						cm = fmm::type;
					} else if(ch != inp_()) {
						err_ = true;
						return;
					}
					break;

				case fmm::type:
					if(ch >= 0x60) ch -= 0x20;
					if(ch == 'B') {
						mode_ = mode::BIN;
					} else if(ch == 'O') {
						mode_ = mode::OCT;
					} else if(ch == 'D') {
						mode_ = mode::DEC;
					} else if(ch == 'X') {
						mode_ = mode::HEX;
					} else if(ch == 'F') {
						mode_ = mode::FLOAT;
					} else {
						err_ = true;
					}
					return;
				}
			}
			if(ch == 0 && inp_() == 0) ;
			else {
				err_ = true;
			}
		}

		bool neg_() {
			bool neg = false;
			auto s = inp_();
			if(s == '-') { neg = true; }
			else if(s == '+') { neg = false; }
			else inp_.unget();
			return neg;
		}

		int32_t nb_int_(bool sign = true)
		{
			auto neg = neg_();

			uint32_t v = 0;
			switch(mode_) {
			case mode::BIN:
				v = bin_();
				break;
			case mode::OCT:
				v = oct_();
				break;
			case mode::DEC:
				v = dec_();
				break;
			case mode::HEX:
				v = hex_();
				break;
			default:
				err_ = true;
				break;
			}
			if(!err_) {
				inp_.unget();
				next_();
				if(!err_) ++num_;
			}
			if(sign && neg) return -static_cast<int32_t>(v);
			else return static_cast<int32_t>(v);
		}

		float nb_real_()
		{
			bool neg = neg_();

			float v = 0.0f;
			switch(mode_) {
			case mode::FLOAT:
				v = real_();
				break;
			default:
				err_ = true;
				break;
			}
			if(!err_) {
				inp_.unget();
				next_();
				if(!err_) ++num_;
			}
			if(neg) return -v;
			else return v;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
			@param[in]	form	入力形式
			@param[in]	inp		変換文字列（nullptrの場合、sci_getch で取得）
		*/
		//-----------------------------------------------------------------//
		basic_input(const char* form, const char* inp = nullptr) : form_(form), inp_(inp),
			mode_(mode::NONE), err_(false), num_(0)
		{
			next_();
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  正常変換数を取得
			@return 正常変換数
		*/
		//-----------------------------------------------------------------//
		int num() const { return num_; }

		//-----------------------------------------------------------------//
		/*!
			@brief  テンプレート・オペレーター「%」
			@param[in]	val	整数型
			@return	自分の参照
		*/
		//-----------------------------------------------------------------//
		template <typename T>
		basic_input& operator % (T& val)
		{
			if(err_) return *this;

			if(std::is_floating_point<T>::value) {
				val = nb_real_();
			} else {
				val = nb_int_(std::is_signed<T>::value);
			}
			return *this;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  オペレーター「=」
		*/
		//-----------------------------------------------------------------//
		basic_input& operator = (const basic_input& in) { return *this; }
	};

	typedef basic_input<def_chainp> input;
}
<|endoftext|>


<commit_before>#include "project1.h"

void Project1::foo(int &i) {
	i = 1;
}

void independentMethod(int &i) {
	i = 0;
}<commit_msg>Delete project1.cpp<commit_after><|endoftext|>