<commit_before>/**
 * Shader.cpp
 * Contributors:
 *      * Arthur Sonzogni (author)
 * Licence:
 *      * Public Domain
 */

#include "Shader.hpp"
#include <vector>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <glm/gtc/type_ptr.hpp>

using namespace std;
using namespace glm;

// file reading
void getFileContents(const char *filename, vector<char>& buffer)
{
    //debug("chargement du fichier : %s",filename);
    ifstream file(filename, ios_base::binary);
    if (file)
    {
        file.seekg(0, ios_base::end);
        streamsize size = file.tellg();
        if (size > 0)
        {
            file.seekg(0, ios_base::beg);
            buffer.resize(static_cast<size_t>(size));
            file.read(&buffer[0], size);
        }
        buffer.push_back('\0');
    }
    else
    {
        throw std::invalid_argument(string("The file ") + filename + " doesn't exists");
    }
}

Shader::Shader(const std::string &filename, GLenum type)
{
    // file loading
    vector<char> fileContent;
    getFileContents(filename.c_str(),fileContent);

    // creation
    handle = glCreateShader(type);
    if(handle == 0)
        throw std::runtime_error("[Error] Impossible to create a new Shader");

    // code source assignation
    const char* shaderText(&fileContent[0]);
    glShaderSource(handle, 1, (const GLchar**)&shaderText, NULL);

    // compilation
    glCompileShader(handle);

    // compilation check
    GLint compile_status;
    glGetShaderiv(handle, GL_COMPILE_STATUS, &compile_status);
    if(compile_status != GL_TRUE)
    {
        /* error text retreiving*/
        GLsizei logsize = 0;
        glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &logsize);

        char* log = new char[logsize+1];
        glGetShaderInfoLog(handle, logsize, &logsize, log);
        //log[logsize]='\0';

        cout<<"[Error] compilation error: "<<filename<<endl;
        cout<<log<<endl;

        exit(EXIT_FAILURE);
    }
    else
    {
        cout<<"[Info] Shader "<<filename<<" compiled successfully"<<endl;
    }
}

GLuint Shader::getHandle() const
{
    return handle;
}

Shader::~Shader()
{
}

ShaderProgram::ShaderProgram()
{
    // programme creation
    handle = glCreateProgram();
    if (not handle)
        throw std::runtime_error("Impossible to create a new shader program");
}

ShaderProgram::ShaderProgram(std::initializer_list<Shader> shaderList):
    ShaderProgram()
{
    for(auto& s : shaderList)
        glAttachShader(handle,s.getHandle());

    link();
}

void ShaderProgram::link()
{
    glLinkProgram(handle);
    GLint result;
    glGetProgramiv(handle,GL_LINK_STATUS, &result);
    if (result!=GL_TRUE)
    {
        cout<<"[Error] linkage error"<<endl;

        /* error text retreiving*/
        GLsizei logsize = 0;
        glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &logsize);

        char* log = new char[logsize];
        glGetProgramInfoLog(handle, logsize, &logsize, log);
        //log[logsize]='\0';

        cout<<log<<endl;
    }
}

GLint ShaderProgram::uniform(const std::string &name)
{
    auto it = uniforms.find(name);
    if (it == uniforms.end())
    {
        // uniform that is not referenced
        GLint r = glGetUniformLocation(handle, name.c_str());
        if ( r == GL_INVALID_OPERATION || r < 0 )
            cout<<"[Error] uniform "<<name<<" doesn't exist in program"<<endl;
        // add it anyways
        uniforms[name] = r;

        return r;
    }
    else
        return it->second;
}

GLint ShaderProgram::attribute(const std::string& name)
{
    GLint attrib = glGetAttribLocation(handle, name.c_str());
    if (attrib == GL_INVALID_OPERATION || attrib < 0 )
        cout<<"[Error] Attribute "<<name<<" doesn't exist in program"<<endl;

    return attrib;
}

void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset,
    GLboolean normalize,
    GLenum type)
{
    GLint loc = attribute(name);
    glEnableVertexAttribArray(loc);
    glVertexAttribPointer(
        loc,
        size,
        type,
        normalize,
        stride,
        reinterpret_cast<void*>(offset)
	);
}

void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset,
        GLboolean normalize)
{
    setAttribute(name,size,stride,offset,normalize,GL_FLOAT);
}

void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset,
        GLenum type)
{
    setAttribute(name,size,stride,offset,false,type);
}

void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset)
{
    setAttribute(name,size,stride,offset,false,GL_FLOAT);
}

void ShaderProgram::setUniform(const std::string& name,float x,float y,float z)
{
    glUniform3f(uniform(name), x, y, z);
}
void ShaderProgram::setUniform(const std::string& name, const vec3 & v)
{
    glUniform3fv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const dvec3 & v)
{
    glUniform3dv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const vec4 & v)
{
    glUniform4fv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const dvec4 & v)
{
    glUniform4dv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const dmat4 & m)
{
    glUniformMatrix4dv(uniform(name), 1, GL_FALSE, value_ptr(m));
}
void ShaderProgram::setUniform(const std::string& name, const mat4 & m)
{
    glUniformMatrix4fv(uniform(name), 1, GL_FALSE, value_ptr(m));
}
void ShaderProgram::setUniform(const std::string& name, const mat3 & m)
{
    glUniformMatrix3fv(uniform(name), 1, GL_FALSE, value_ptr(m));
}
void ShaderProgram::setUniform(const std::string& name, float val )
{
    glUniform1f(uniform(name), val);
}
void ShaderProgram::setUniform(const std::string& name, int val )
{
    glUniform1i(uniform(name), val);
}

ShaderProgram::~ShaderProgram()
{
    //glDeleteProgram(handle);
}

void ShaderProgram::use() const
{
    glUseProgram(handle);
}
void ShaderProgram::unuse() const
{
    glUseProgram(0);
}

GLuint ShaderProgram::getHandle() const
{
    return handle;
}
<commit_msg>Fix missing header<commit_after>/**
 * Shader.cpp
 * Contributors:
 *      * Arthur Sonzogni (author)
 * Licence:
 *      * Public Domain
 */

#include "Shader.hpp"
#include <vector>
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <stdexcept>
#include <glm/gtc/type_ptr.hpp>

using namespace std;
using namespace glm;

// file reading
void getFileContents(const char *filename, vector<char>& buffer)
{
    //debug("chargement du fichier : %s",filename);
    ifstream file(filename, ios_base::binary);
    if (file)
    {
        file.seekg(0, ios_base::end);
        streamsize size = file.tellg();
        if (size > 0)
        {
            file.seekg(0, ios_base::beg);
            buffer.resize(static_cast<size_t>(size));
            file.read(&buffer[0], size);
        }
        buffer.push_back('\0');
    }
    else
    {
        throw std::invalid_argument(string("The file ") + filename + " doesn't exists");
    }
}

Shader::Shader(const std::string &filename, GLenum type)
{
    // file loading
    vector<char> fileContent;
    getFileContents(filename.c_str(),fileContent);

    // creation
    handle = glCreateShader(type);
    if(handle == 0)
        throw std::runtime_error("[Error] Impossible to create a new Shader");

    // code source assignation
    const char* shaderText(&fileContent[0]);
    glShaderSource(handle, 1, (const GLchar**)&shaderText, NULL);

    // compilation
    glCompileShader(handle);

    // compilation check
    GLint compile_status;
    glGetShaderiv(handle, GL_COMPILE_STATUS, &compile_status);
    if(compile_status != GL_TRUE)
    {
        /* error text retreiving*/
        GLsizei logsize = 0;
        glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &logsize);

        char* log = new char[logsize+1];
        glGetShaderInfoLog(handle, logsize, &logsize, log);
        //log[logsize]='\0';

        cout<<"[Error] compilation error: "<<filename<<endl;
        cout<<log<<endl;

        exit(EXIT_FAILURE);
    }
    else
    {
        cout<<"[Info] Shader "<<filename<<" compiled successfully"<<endl;
    }
}

GLuint Shader::getHandle() const
{
    return handle;
}

Shader::~Shader()
{
}

ShaderProgram::ShaderProgram()
{
    // programme creation
    handle = glCreateProgram();
    if (not handle)
        throw std::runtime_error("Impossible to create a new shader program");
}

ShaderProgram::ShaderProgram(std::initializer_list<Shader> shaderList):
    ShaderProgram()
{
    for(auto& s : shaderList)
        glAttachShader(handle,s.getHandle());

    link();
}

void ShaderProgram::link()
{
    glLinkProgram(handle);
    GLint result;
    glGetProgramiv(handle,GL_LINK_STATUS, &result);
    if (result!=GL_TRUE)
    {
        cout<<"[Error] linkage error"<<endl;

        /* error text retreiving*/
        GLsizei logsize = 0;
        glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &logsize);

        char* log = new char[logsize];
        glGetProgramInfoLog(handle, logsize, &logsize, log);
        //log[logsize]='\0';

        cout<<log<<endl;
    }
}

GLint ShaderProgram::uniform(const std::string &name)
{
    auto it = uniforms.find(name);
    if (it == uniforms.end())
    {
        // uniform that is not referenced
        GLint r = glGetUniformLocation(handle, name.c_str());
        if ( r == GL_INVALID_OPERATION || r < 0 )
            cout<<"[Error] uniform "<<name<<" doesn't exist in program"<<endl;
        // add it anyways
        uniforms[name] = r;

        return r;
    }
    else
        return it->second;
}

GLint ShaderProgram::attribute(const std::string& name)
{
    GLint attrib = glGetAttribLocation(handle, name.c_str());
    if (attrib == GL_INVALID_OPERATION || attrib < 0 )
        cout<<"[Error] Attribute "<<name<<" doesn't exist in program"<<endl;

    return attrib;
}

void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset,
    GLboolean normalize,
    GLenum type)
{
    GLint loc = attribute(name);
    glEnableVertexAttribArray(loc);
    glVertexAttribPointer(
        loc,
        size,
        type,
        normalize,
        stride,
        reinterpret_cast<void*>(offset)
	);
}

void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset,
        GLboolean normalize)
{
    setAttribute(name,size,stride,offset,normalize,GL_FLOAT);
}

void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset,
        GLenum type)
{
    setAttribute(name,size,stride,offset,false,type);
}

void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset)
{
    setAttribute(name,size,stride,offset,false,GL_FLOAT);
}

void ShaderProgram::setUniform(const std::string& name,float x,float y,float z)
{
    glUniform3f(uniform(name), x, y, z);
}
void ShaderProgram::setUniform(const std::string& name, const vec3 & v)
{
    glUniform3fv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const dvec3 & v)
{
    glUniform3dv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const vec4 & v)
{
    glUniform4fv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const dvec4 & v)
{
    glUniform4dv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const dmat4 & m)
{
    glUniformMatrix4dv(uniform(name), 1, GL_FALSE, value_ptr(m));
}
void ShaderProgram::setUniform(const std::string& name, const mat4 & m)
{
    glUniformMatrix4fv(uniform(name), 1, GL_FALSE, value_ptr(m));
}
void ShaderProgram::setUniform(const std::string& name, const mat3 & m)
{
    glUniformMatrix3fv(uniform(name), 1, GL_FALSE, value_ptr(m));
}
void ShaderProgram::setUniform(const std::string& name, float val )
{
    glUniform1f(uniform(name), val);
}
void ShaderProgram::setUniform(const std::string& name, int val )
{
    glUniform1i(uniform(name), val);
}

ShaderProgram::~ShaderProgram()
{
    //glDeleteProgram(handle);
}

void ShaderProgram::use() const
{
    glUseProgram(handle);
}
void ShaderProgram::unuse() const
{
    glUseProgram(0);
}

GLuint ShaderProgram::getHandle() const
{
    return handle;
}
<|endoftext|>


<commit_before>#include "gui/coordinate.h"

#include "globals.h"

using namespace Gui;

static int getHorizontalAbsolute(double x){
    const int center = Global::getScreenWidth()/2;
    return (int)(center + (center * x));
}

static int getVerticalAbsolute(double y){
    const int center = Global::getScreenHeight()/2;
    return (int)(center + (center * y));
}

static double getHorizontalRelative(int x){
    const int center = Global::getScreenWidth()/2;
    if (x == center){
        return 0;
    } else if (x < center){
        return -( (x/center) * .01);
    } else if (x > center){
        return ( ((x - center)/center) * .01);
    }
    return 0;
}

static double getVerticalRelative(int y){
    const int center = Global::getScreenHeight()/2;
    if (y == center){
        return 0;
    } else if (y < center){
        return -( (y/center) * .01);
    } else if (y > center){
        return ( ((y - center)/center) * .01);
    }
    return 0;
}

AbsolutePoint::AbsolutePoint(){
}
AbsolutePoint::AbsolutePoint(int x, int y){
}
AbsolutePoint::~AbsolutePoint(){
}
int AbsolutePoint::getX(){
    return x;
}
int AbsolutePoint::getY(){
    return y;
}

RelativePoint::RelativePoint(){
}
RelativePoint::RelativePoint(double x, double y){
}
RelativePoint::~RelativePoint(){
}
int RelativePoint::getX(){
    return getHorizontalAbsolute(x);
}
int RelativePoint::getY(){
    return getVerticalAbsolute(y);
}
AbsolutePoint RelativePoint::getAbsolute(){
    return AbsolutePoint(getHorizontalAbsolute(x),getVerticalAbsolute(y));
}
double RelativePoint::getRelativeX(){
    return x;
}
double RelativePoint::getRelativeY(){
    return y;
}

Coordinate::Coordinate(){
}
Coordinate::Coordinate(const AbsolutePoint &, const AbsolutePoint &){
}
Coordinate::Coordinate(const RelativePoint &, const RelativePoint &){
}
Coordinate::~Coordinate(){
}
void Coordinate::setZ(double z){
}
void Coordinate::setRadius(double radius){
}
int Coordinate::getX(){
    return position.getX();
}
int Coordinate::getY(){
    return position.getY();
}
int Coordinate::getWidth(){
    return dimensions.getX();
}
int Coordinate::getHeight(){
    return dimensions.getY();
}

<commit_msg>Clean up relative/absolute conversions<commit_after>#include "gui/coordinate.h"

#include "globals.h"

using namespace Gui;

static int relativeToAbsolute(double x, int center){
    return (int)(center + (center * x));
}

static double absoluteToRelative(int x, int center){
    return (x-center)/center;
}

AbsolutePoint::AbsolutePoint(){
}
AbsolutePoint::AbsolutePoint(int x, int y){
}
AbsolutePoint::~AbsolutePoint(){
}
int AbsolutePoint::getX(){
    return x;
}
int AbsolutePoint::getY(){
    return y;
}

RelativePoint::RelativePoint(){
}
RelativePoint::RelativePoint(double x, double y){
}
RelativePoint::~RelativePoint(){
}
int RelativePoint::getX(){
    return relativeToAbsolute(x,Global::getScreenWidth()/2);
}
int RelativePoint::getY(){
    return relativeToAbsolute(y,Global::getScreenHeight()/2);
}
AbsolutePoint RelativePoint::getAbsolute(){
    return AbsolutePoint(relativeToAbsolute(x,Global::getScreenWidth()/2), relativeToAbsolute(y,Global::getScreenHeight()/2));
}
double RelativePoint::getRelativeX(){
    return x;
}
double RelativePoint::getRelativeY(){
    return y;
}

Coordinate::Coordinate(){
}
Coordinate::Coordinate(const AbsolutePoint &, const AbsolutePoint &){
}
Coordinate::Coordinate(const RelativePoint &, const RelativePoint &){
}
Coordinate::~Coordinate(){
}
void Coordinate::setZ(double z){
}
void Coordinate::setRadius(double radius){
}
int Coordinate::getX(){
    return position.getX();
}
int Coordinate::getY(){
    return position.getY();
}
int Coordinate::getWidth(){
    return dimensions.getX();
}
int Coordinate::getHeight(){
    return dimensions.getY();
}

<|endoftext|>


<commit_before>#include "fallbackedgedb.h"

#include <fstream>
#include <limits>

using namespace annis;
using namespace std;

FallbackEdgeDB::FallbackEdgeDB(StringStorage &strings, const Component &component)
  : strings(strings), component(component)
{
}

void FallbackEdgeDB::addEdge(const Edge &edge)
{
  if(edge.source != edge.target)
  {
    edges.insert(edge);
  }
}

void FallbackEdgeDB::addEdgeAnnotation(const Edge& edge, const Annotation &anno)
{
  edgeAnnotations.insert2(edge, anno);
}

void FallbackEdgeDB::clear()
{
  edges.clear();
  edgeAnnotations.clear();
}

bool FallbackEdgeDB::isConnected(const Edge &edge, unsigned int minDistance, unsigned int maxDistance) const
{
  typedef stx::btree_set<Edge>::const_iterator EdgeIt;
  if(minDistance == 1 && maxDistance == 1)
  {
    EdgeIt it = edges.find(edge);
    if(it != edges.end())
    {
      return true;
    }
    else
    {
      return false;
    }
  }
  else
  {
    FallbackDFSIterator dfs(*this, edge.source, minDistance, maxDistance);
    DFSIteratorResult result = dfs.nextDFS();
    while(result.found)
    {
      if(result.node == edge.target)
      {
        return true;
      }
      result = dfs.nextDFS();
    }
  }

  return false;
}

std::unique_ptr<EdgeIterator> FallbackEdgeDB::findConnected(nodeid_t sourceNode,
                                                 unsigned int minDistance,
                                                 unsigned int maxDistance) const
{
  return std::unique_ptr<EdgeIterator>(
        new FallbackDFSIterator(*this, sourceNode, minDistance, maxDistance));
}

int FallbackEdgeDB::distance(const Edge &edge) const
{
  FallbackDFSIterator dfs(*this, edge.source, 0, uintmax);
  DFSIteratorResult result = dfs.nextDFS();
  while(result.found)
  {
    if(result.node == edge.target)
    {
      return result.distance;
    }
    result = dfs.nextDFS();
  }
  return -1;
}

std::vector<Annotation> FallbackEdgeDB::getEdgeAnnotations(const Edge& edge) const
{
  typedef stx::btree_multimap<Edge, Annotation>::const_iterator ItType;

  std::vector<Annotation> result;

  std::pair<ItType, ItType> range =
      edgeAnnotations.equal_range(edge);

  for(ItType it=range.first; it != range.second; ++it)
  {
    result.push_back(it->second);
  }

  return result;
}

std::vector<nodeid_t> FallbackEdgeDB::getOutgoingEdges(nodeid_t node) const
{
  typedef stx::btree_set<Edge>::const_iterator EdgeIt;

  vector<nodeid_t> result;

  EdgeIt lowerIt = edges.lower_bound(Init::initEdge(node, numeric_limits<uint32_t>::min()));
  EdgeIt upperIt = edges.upper_bound(Init::initEdge(node, numeric_limits<uint32_t>::max()));

  for(EdgeIt it = lowerIt; it != upperIt; it++)
  {
    result.push_back(it->target);
  }

  return result;
}

std::vector<nodeid_t> FallbackEdgeDB::getIncomingEdges(nodeid_t node) const
{
  // this is a extremly slow approach, there should be more efficient methods for other
  // edge databases
  // TODO: we should also concider to add another index

  std::vector<nodeid_t> result;
  result.reserve(10);
  for(auto& e : edges)
  {
    if(e.target == node)
    {
      result.push_back(e.source);
    }
  }
  return result;
}

bool FallbackEdgeDB::load(std::string dirPath)
{
  clear();

  ifstream in;

  in.open(dirPath + "/edges.btree");
  edges.restore(in);
  in.close();

  in.open(dirPath + "/edgeAnnotations.btree");
  edgeAnnotations.restore(in);
  in.close();

  return true;

}

bool FallbackEdgeDB::save(std::string dirPath)
{
  ofstream out;

  out.open(dirPath + "/edges.btree");
  edges.dump(out);
  out.close();

  out.open(dirPath + "/edgeAnnotations.btree");
  edgeAnnotations.dump(out);
  out.close();

  return true;
}

std::uint32_t FallbackEdgeDB::numberOfEdges() const
{
  return edges.size();
}

std::uint32_t FallbackEdgeDB::numberOfEdgeAnnotations() const
{
  return edgeAnnotations.size();
}

FallbackDFSIterator::FallbackDFSIterator(const FallbackEdgeDB &edb,
                                                     std::uint32_t startNode,
                                                     unsigned int minDistance,
                                                     unsigned int maxDistance)
  : edb(edb), minDistance(minDistance), maxDistance(maxDistance), startNode(startNode)
{
  initStack();
}

DFSIteratorResult FallbackDFSIterator::nextDFS()
{
  DFSIteratorResult result;
  result.found = false;

  while(!result.found && !traversalStack.empty())
  {
    pair<uint32_t, unsigned int> stackEntry = traversalStack.top();
    result.node = stackEntry.first;
    result.distance = stackEntry.second;
    traversalStack.pop();

    if(result.distance >= minDistance && result.distance <= maxDistance)
    {
      // get the next node
      result.found = true;
    }

    // add the remaining child nodes
    if(result.distance < maxDistance)
    {
      // add the outgoing edges to the stack
      auto outgoing = edb.getOutgoingEdges(result.node);
      for(size_t idxOutgoing=0; idxOutgoing < outgoing.size(); idxOutgoing++)
      {
        if(visited.find(outgoing[idxOutgoing]) == visited.end())
        {
          traversalStack.push(pair<nodeid_t, unsigned int>(outgoing[idxOutgoing],
                                                           result.distance+1));
          visited.insert(outgoing[idxOutgoing]);
        }
      }
    }
  }
  return result;
}

std::pair<bool, nodeid_t> FallbackDFSIterator::next()
{
  DFSIteratorResult result = nextDFS();
  return std::pair<bool, nodeid_t>(result.found, result.node);
}

void FallbackDFSIterator::initStack()
{
  // add the initial value to the stack
  traversalStack.push(pair<uint32_t,unsigned int>(startNode, 0));
  visited.insert(startNode);
}

void FallbackDFSIterator::reset()
{
  // clear the stack
  while(!traversalStack.empty())
  {
    traversalStack.pop();
  }
  visited.clear();

  initStack();
}
<commit_msg>use iterator for looping over the outgoing edges<commit_after>#include "fallbackedgedb.h"

#include <fstream>
#include <limits>

using namespace annis;
using namespace std;

FallbackEdgeDB::FallbackEdgeDB(StringStorage &strings, const Component &component)
  : strings(strings), component(component)
{
}

void FallbackEdgeDB::addEdge(const Edge &edge)
{
  if(edge.source != edge.target)
  {
    edges.insert(edge);
  }
}

void FallbackEdgeDB::addEdgeAnnotation(const Edge& edge, const Annotation &anno)
{
  edgeAnnotations.insert2(edge, anno);
}

void FallbackEdgeDB::clear()
{
  edges.clear();
  edgeAnnotations.clear();
}

bool FallbackEdgeDB::isConnected(const Edge &edge, unsigned int minDistance, unsigned int maxDistance) const
{
  typedef stx::btree_set<Edge>::const_iterator EdgeIt;
  if(minDistance == 1 && maxDistance == 1)
  {
    EdgeIt it = edges.find(edge);
    if(it != edges.end())
    {
      return true;
    }
    else
    {
      return false;
    }
  }
  else
  {
    FallbackDFSIterator dfs(*this, edge.source, minDistance, maxDistance);
    DFSIteratorResult result = dfs.nextDFS();
    while(result.found)
    {
      if(result.node == edge.target)
      {
        return true;
      }
      result = dfs.nextDFS();
    }
  }

  return false;
}

std::unique_ptr<EdgeIterator> FallbackEdgeDB::findConnected(nodeid_t sourceNode,
                                                 unsigned int minDistance,
                                                 unsigned int maxDistance) const
{
  return std::unique_ptr<EdgeIterator>(
        new FallbackDFSIterator(*this, sourceNode, minDistance, maxDistance));
}

int FallbackEdgeDB::distance(const Edge &edge) const
{
  FallbackDFSIterator dfs(*this, edge.source, 0, uintmax);
  DFSIteratorResult result = dfs.nextDFS();
  while(result.found)
  {
    if(result.node == edge.target)
    {
      return result.distance;
    }
    result = dfs.nextDFS();
  }
  return -1;
}

std::vector<Annotation> FallbackEdgeDB::getEdgeAnnotations(const Edge& edge) const
{
  typedef stx::btree_multimap<Edge, Annotation>::const_iterator ItType;

  std::vector<Annotation> result;

  std::pair<ItType, ItType> range =
      edgeAnnotations.equal_range(edge);

  for(ItType it=range.first; it != range.second; ++it)
  {
    result.push_back(it->second);
  }

  return result;
}

std::vector<nodeid_t> FallbackEdgeDB::getOutgoingEdges(nodeid_t node) const
{
  typedef stx::btree_set<Edge>::const_iterator EdgeIt;

  vector<nodeid_t> result;

  EdgeIt lowerIt = edges.lower_bound(Init::initEdge(node, numeric_limits<uint32_t>::min()));
  EdgeIt upperIt = edges.upper_bound(Init::initEdge(node, numeric_limits<uint32_t>::max()));

  for(EdgeIt it = lowerIt; it != upperIt; it++)
  {
    result.push_back(it->target);
  }

  return result;
}

std::vector<nodeid_t> FallbackEdgeDB::getIncomingEdges(nodeid_t node) const
{
  // this is a extremly slow approach, there should be more efficient methods for other
  // edge databases
  // TODO: we should also concider to add another index

  std::vector<nodeid_t> result;
  result.reserve(10);
  for(auto& e : edges)
  {
    if(e.target == node)
    {
      result.push_back(e.source);
    }
  }
  return result;
}

bool FallbackEdgeDB::load(std::string dirPath)
{
  clear();

  ifstream in;

  in.open(dirPath + "/edges.btree");
  edges.restore(in);
  in.close();

  in.open(dirPath + "/edgeAnnotations.btree");
  edgeAnnotations.restore(in);
  in.close();

  return true;

}

bool FallbackEdgeDB::save(std::string dirPath)
{
  ofstream out;

  out.open(dirPath + "/edges.btree");
  edges.dump(out);
  out.close();

  out.open(dirPath + "/edgeAnnotations.btree");
  edgeAnnotations.dump(out);
  out.close();

  return true;
}

std::uint32_t FallbackEdgeDB::numberOfEdges() const
{
  return edges.size();
}

std::uint32_t FallbackEdgeDB::numberOfEdgeAnnotations() const
{
  return edgeAnnotations.size();
}

FallbackDFSIterator::FallbackDFSIterator(const FallbackEdgeDB &edb,
                                                     std::uint32_t startNode,
                                                     unsigned int minDistance,
                                                     unsigned int maxDistance)
  : edb(edb), minDistance(minDistance), maxDistance(maxDistance), startNode(startNode)
{
  initStack();
}

DFSIteratorResult FallbackDFSIterator::nextDFS()
{
  DFSIteratorResult result;
  result.found = false;

  while(!result.found && !traversalStack.empty())
  {
    pair<uint32_t, unsigned int> stackEntry = traversalStack.top();
    result.node = stackEntry.first;
    result.distance = stackEntry.second;
    traversalStack.pop();

    if(result.distance >= minDistance && result.distance <= maxDistance)
    {
      // get the next node
      result.found = true;
    }

    // add the remaining child nodes
    if(result.distance < maxDistance)
    {
      // add the outgoing edges to the stack
      auto outgoing = edb.getOutgoingEdges(result.node);
      for(const auto& outNodeID : outgoing)
      {
        if(visited.find(outNodeID) == visited.end())
        {
          traversalStack.push(pair<nodeid_t, unsigned int>(outNodeID,
                                                           result.distance+1));
          visited.insert(outNodeID);
        }
      }
    }
  }
  return result;
}

std::pair<bool, nodeid_t> FallbackDFSIterator::next()
{
  DFSIteratorResult result = nextDFS();
  return std::pair<bool, nodeid_t>(result.found, result.node);
}

void FallbackDFSIterator::initStack()
{
  // add the initial value to the stack
  traversalStack.push(pair<uint32_t,unsigned int>(startNode, 0));
  visited.insert(startNode);
}

void FallbackDFSIterator::reset()
{
  // clear the stack
  while(!traversalStack.empty())
  {
    traversalStack.pop();
  }
  visited.clear();

  initStack();
}
<|endoftext|>


<commit_before>//
//  GLWarpShader.cpp
//  gatherer
//
//  Created by David Hirvonen on 8/28/15.
//
//

#include "graphics/GLWarpShader.h"
#include "graphics/RenderTexture.h"
#include "graphics/GLTexture.h"
#include "graphics/GLExtra.h"

_GATHERER_GRAPHICS_BEGIN

WarpShader::WarpShader(const cv::Size &size, const cv::Point2f &resolution)
: m_size(size)
, m_resolution(resolution)
{
    compileShadersPlanar();
}

void WarpShader::compileShadersPlanar()
{
    using gatherer::graphics::RenderTexture;

    // vertex shader
    const char *kPlanarVertexShaderString = R"(
    attribute vec4 position;
    attribute vec4 inputTextureCoordinate;
    varying vec2 textureCoordinate;
    uniform mat4 modelViewProjMatrix;
    void main()
    {
        gl_Position = modelViewProjMatrix * position;
        textureCoordinate = inputTextureCoordinate.xy;
    })";

    const char *kPlanarFragmentShaderString =
#if defined(GATHERER_OPENGL_ES)
    "varying highp vec2 textureCoordinate;\n"
#else
    "varying vec2 textureCoordinate;\n"
#endif
    R"(
    uniform sampler2D texture;
    void main()
    {
        gl_FragColor = texture2D(texture, textureCoordinate);
    })";

    // m_frameVertices, i.e. (0, 0, w, h)
    // m_textureCoordinates, i.e. (-1, -1, 1, 1)
    const GLchar * vShaderStr[] = { kPlanarVertexShaderString };
    const GLchar * fShaderStr[] = { kPlanarFragmentShaderString };
    std::vector< std::pair<int, const char *> > attributes;
    attributes.push_back( std::pair<int, const char*>(RenderTexture::ATTRIB_VERTEX, "position") );
    attributes.push_back( std::pair<int, const char*>(RenderTexture::ATTRIB_TEXTUREPOSITION, "inputTextureCoordinate") );

    m_pPlanarShaderProgram = std::make_unique<gatherer::graphics::shader_prog>(vShaderStr, fShaderStr, attributes);
    m_PlanarUniformMVP = m_pPlanarShaderProgram->GetUniformLocation("modelViewProjMatrix");
    m_PlanarUniformTexture =  m_pPlanarShaderProgram->GetUniformLocation("texture");

    gatherer::graphics::glErrorTest();
}

GLuint WarpShader::operator()(int texture)
{
    const float w = m_size.width;
    const float h = m_size.height;

    // Transform to rectangle defined by (-1,-1) (+1,+1)
    cv::Matx33f T(1,0,-w/2,0,1,-h/2,0,0,1);
    cv::Matx33f S(2.0/w,0,0,0,2.0/h,0,0,0,1);

    // Otionally add some effect:
    const float theta = (m_count % 360) * M_PI / 180.f;
    const float c = std::cos(theta);
    const float s = std::sin(theta);
    cv::Matx33f R(+c, -s, 0, +s, +c, 0, 0, 0, 1);
    cv::Matx33f H = S * R * T;

    (*this)(texture, H);

    m_count ++;

    return 0;
}

void WarpShader::operator()(int texture, const cv::Matx33f &H)
{
    using gatherer::graphics::RenderTexture;
    using gatherer::graphics::GLTexRect;

    cv::Matx44f MVPt;
    R3x3To4x4(H.t(), MVPt);

    GLTexRect roi(m_size);

    // {-1,-1}, {1,-1}, {-1,1}, {1,1}
    auto vertices = roi.GetVertices();
    auto coords = GLTexRect::GetTextureCoordinates();

    std::vector<cv::Vec4f> vertices4d;
    for(const auto &p : vertices)
        vertices4d.emplace_back(p.x, (m_size.height - p.y), 0, 1);

    // Note: We'll assume this is configured by the calling functions
    // Note: for rendering to the display we need to factor in screen resolution
    //glViewport(0, 0, int(m_resolution.x * m_size.width + 0.5f), int(m_resolution.y * m_size.height + 0.5f));

    (*m_pPlanarShaderProgram)();
    glUniformMatrix4fv(m_PlanarUniformMVP, 1, 0, (GLfloat *)&MVPt(0,0));

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);
    glBindTexture(GL_TEXTURE_2D, texture);

    //std::cout << "glBindTexture " << int(glGetError()) << std::endl;

    glVertexAttribPointer(RenderTexture::ATTRIB_VERTEX, 4, GL_FLOAT, 0, 0, &vertices4d[0][0]);
    glEnableVertexAttribArray(RenderTexture::ATTRIB_VERTEX);
    glVertexAttribPointer(RenderTexture::ATTRIB_TEXTUREPOSITION, 2, GL_FLOAT, 0, 0, &coords[0]);
    glEnableVertexAttribArray(RenderTexture::ATTRIB_TEXTUREPOSITION);

    //std::cout << "glVertex stuff " << int(glGetError()) << std::endl;

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}

_GATHERER_GRAPHICS_END
<commit_msg>return to c++11 without c++14 make_unique TODO<commit_after>//
//  GLWarpShader.cpp
//  gatherer
//
//  Created by David Hirvonen on 8/28/15.
//
//

#include "graphics/GLWarpShader.h"
#include "graphics/RenderTexture.h"
#include "graphics/GLTexture.h"
#include "graphics/GLExtra.h"

_GATHERER_GRAPHICS_BEGIN

WarpShader::WarpShader(const cv::Size &size, const cv::Point2f &resolution)
: m_size(size)
, m_resolution(resolution)
{
    compileShadersPlanar();
}

void WarpShader::compileShadersPlanar()
{
    using gatherer::graphics::RenderTexture;

    // vertex shader
    const char *kPlanarVertexShaderString = R"(
    attribute vec4 position;
    attribute vec4 inputTextureCoordinate;
    varying vec2 textureCoordinate;
    uniform mat4 modelViewProjMatrix;
    void main()
    {
        gl_Position = modelViewProjMatrix * position;
        textureCoordinate = inputTextureCoordinate.xy;
    })";

    const char *kPlanarFragmentShaderString =
#if defined(GATHERER_OPENGL_ES)
    "varying highp vec2 textureCoordinate;\n"
#else
    "varying vec2 textureCoordinate;\n"
#endif
    R"(
    uniform sampler2D texture;
    void main()
    {
        gl_FragColor = texture2D(texture, textureCoordinate);
    })";

    // m_frameVertices, i.e. (0, 0, w, h)
    // m_textureCoordinates, i.e. (-1, -1, 1, 1)
    const GLchar * vShaderStr[] = { kPlanarVertexShaderString };
    const GLchar * fShaderStr[] = { kPlanarFragmentShaderString };
    std::vector< std::pair<int, const char *> > attributes;
    attributes.push_back( std::pair<int, const char*>(RenderTexture::ATTRIB_VERTEX, "position") );
    attributes.push_back( std::pair<int, const char*>(RenderTexture::ATTRIB_TEXTUREPOSITION, "inputTextureCoordinate") );

    m_pPlanarShaderProgram = make_unique<gatherer::graphics::shader_prog>(vShaderStr, fShaderStr, attributes);
    m_PlanarUniformMVP = m_pPlanarShaderProgram->GetUniformLocation("modelViewProjMatrix");
    m_PlanarUniformTexture =  m_pPlanarShaderProgram->GetUniformLocation("texture");

    gatherer::graphics::glErrorTest();
}

GLuint WarpShader::operator()(int texture)
{
    const float w = m_size.width;
    const float h = m_size.height;

    // Transform to rectangle defined by (-1,-1) (+1,+1)
    cv::Matx33f T(1,0,-w/2,0,1,-h/2,0,0,1);
    cv::Matx33f S(2.0/w,0,0,0,2.0/h,0,0,0,1);

    // Otionally add some effect:
    const float theta = (m_count % 360) * M_PI / 180.f;
    const float c = std::cos(theta);
    const float s = std::sin(theta);
    cv::Matx33f R(+c, -s, 0, +s, +c, 0, 0, 0, 1);
    cv::Matx33f H = S * R * T;

    (*this)(texture, H);

    m_count ++;

    return 0;
}

void WarpShader::operator()(int texture, const cv::Matx33f &H)
{
    using gatherer::graphics::RenderTexture;
    using gatherer::graphics::GLTexRect;

    cv::Matx44f MVPt;
    R3x3To4x4(H.t(), MVPt);

    GLTexRect roi(m_size);

    // {-1,-1}, {1,-1}, {-1,1}, {1,1}
    auto vertices = roi.GetVertices();
    auto coords = GLTexRect::GetTextureCoordinates();

    std::vector<cv::Vec4f> vertices4d;
    for(const auto &p : vertices)
        vertices4d.emplace_back(p.x, (m_size.height - p.y), 0, 1);

    // Note: We'll assume this is configured by the calling functions
    // Note: for rendering to the display we need to factor in screen resolution
    //glViewport(0, 0, int(m_resolution.x * m_size.width + 0.5f), int(m_resolution.y * m_size.height + 0.5f));

    (*m_pPlanarShaderProgram)();
    glUniformMatrix4fv(m_PlanarUniformMVP, 1, 0, (GLfloat *)&MVPt(0,0));

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);
    glBindTexture(GL_TEXTURE_2D, texture);

    //std::cout << "glBindTexture " << int(glGetError()) << std::endl;

    glVertexAttribPointer(RenderTexture::ATTRIB_VERTEX, 4, GL_FLOAT, 0, 0, &vertices4d[0][0]);
    glEnableVertexAttribArray(RenderTexture::ATTRIB_VERTEX);
    glVertexAttribPointer(RenderTexture::ATTRIB_TEXTUREPOSITION, 2, GL_FLOAT, 0, 0, &coords[0]);
    glEnableVertexAttribArray(RenderTexture::ATTRIB_TEXTUREPOSITION);

    //std::cout << "glVertex stuff " << int(glGetError()) << std::endl;

    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}

_GATHERER_GRAPHICS_END
<|endoftext|>


<commit_before>#include "util/bitmap.h"
#include "util/trans-bitmap.h"
#include "tabbed-box.h"

#include "menu/menu.h"

#include "util/font.h"

#include "gui/context-box.h"

using namespace Gui;

#if 0
/* FIXME add rounded tabs */
static void roundTab( const Bitmap & work, int radius, int x1, int y1, int x2, int y2, int color, bool bottom = true ){
    const int width = x2 - x1;
    const int height = y2 - y1;
    radius = Mid(0, radius, Min((x1+width - x1)/2, (y1+height - y1)/2));

    work.circleFill(x1+radius, y1+radius, radius, color);
    work.circleFill((x1+width)-radius, y1+radius, radius, color);
    work.circleFill(x1+radius, (y1+height)-radius, radius, color);
    work.circleFill((x1+width)-radius, (y1+height)-radius, radius, color);
    work.rectangleFill( x1+radius, y1, x2-radius, y1+radius, color);
    work.rectangleFill( x1, y1+radius, x2, y2-radius, color);
    work.rectangleFill( x1+radius, y2-radius, x2-radius, y2, color);

    work.line(x1+radius, y1, x1+width-radius, y1, color);
    work.line(x1+radius, y1+height, x1+width-radius,y1+height, color);
    work.line(x1, y1+radius,x1, y1+height-radius, color);
    work.line(x1+width, y1+radius,x1+width, y1+height-radius, color);

    arc(work, x1+radius, y1+radius, S_PI-1.115, radius, color);
    arc(work, x1+radius + (width - radius *2), y1+radius, -S_PI/2 +0.116, radius, color);
    arc(work, x1+width-radius, y1+height-radius, -0.110, radius ,color);
    arc(work, x1+radius, y1+height-radius, S_PI/2-0.119, radius, color);
}
#endif

Tab::Tab():
context(new ContextBox()),
active(false){
    // Set alpha to 0 as we are not interested in the box
    context->colors.borderAlpha = 0;
    context->colors.bodyAlpha = 0;
}

Tab::~Tab(){
    delete context;
}

TabbedBox::TabbedBox():
current(0),
fontWidth(24),
fontHeight(24),
inTab(false),
tabWidthMax(0),
tabFontColor(Bitmap::makeColor(255,255,255)),
currentTabFontColor(Bitmap::makeColor(0,0,255)){
    activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}

TabbedBox::TabbedBox(const TabbedBox & b):
activeTabFontColor(NULL){
    this->location = b.location;
    this->workArea = b.workArea;
}

TabbedBox::~TabbedBox(){
    for (std::vector<Gui::Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
        Gui::Tab * tab = *i;
        if (tab){
            delete tab;
        }
    }

    if (activeTabFontColor){
	delete activeTabFontColor;
    }
}

TabbedBox &TabbedBox::operator=( const TabbedBox &copy){
    location = copy.location;
    workArea = copy.workArea;

    return *this;
}

// Logic
void TabbedBox::act(){
    if (!tabs.empty()){
	const Font & vFont = Font::getFont(font, fontWidth, fontHeight);
	//tabWidthMax = location.getWidth()/tabs.size();
	const int width = vFont.textLength(tabs[current]->name.c_str()) + 5;
	tabWidthMax = (location.getWidth() - width) / (tabs.size() - 1);
    } else {
	return;
    }
    if (!tabs[current]->active){
	tabs[current]->active = true;
    }
    tabs[current]->context->act();
    if (inTab){
	if (activeTabFontColor){
	    activeTabFontColor->update();
	}
    }
}

// Render
void TabbedBox::render(const Bitmap & work){
    const int tabHeight = fontHeight + 5;
    // checkWorkArea();
    Bitmap area(work, location.getX(), location.getY(), location.getWidth(), location.getHeight());
    // Check if we are using a rounded box
    if (location.getRadius() > 0){
        //roundRectFill( *workArea, (int)location.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.body );
        //roundRect( *workArea, (int)location.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.border );
    } else {
        area.translucent().rectangleFill(0, tabHeight+1, location.getWidth()-1, location.getHeight()-1, colors.body );
        //area.translucent().rectangle(0, tabHeight, location.getWidth()-1, location.getHeight()-1, colors.border );
	area.translucent().vLine(tabHeight,0,location.getHeight()-1,colors.border);
	area.translucent().hLine(0,location.getHeight()-1,location.getWidth()-1,colors.border);
	area.translucent().vLine(tabHeight,location.getWidth()-1,location.getHeight()-1,colors.border);
    }

    tabs[current]->context->render(area);

    renderTabs(area);

    /* FIXME: only render the background in translucent mode, the text should
     * not be translucent
     */
    // workArea->draw(location.getX(), location.getY(), work);
}

// Add tab
void TabbedBox::addTab(const std::string & name, const std::vector<ContextItem *> & list){
    for (std::vector<Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
	Tab * tab = *i;
	if (tab->name == name){
	    return;
	}
    }
    Tab * tab = new Tab();
    tab->name = name;
    tab->context->setList(list);
    tab->context->setFont(font, fontWidth, fontHeight);
    const int modifier = fontHeight * .35;
    tab->context->location.setPosition(Gui::AbsolutePoint(0, fontHeight + modifier));
    tab->context->location.setPosition2(Gui::AbsolutePoint(location.getWidth(), location.getHeight()- modifier));
    tab->context->open();
    tabs.push_back(tab);
}

void TabbedBox::moveTab(int direction){
    tabs[current]->context->close();
    tabs[current]->active = false;
    current = (current + direction + tabs.size()) % tabs.size();
    /*
    if (current == 0){
        current = tabs.size()-1;
    } else {
        current--;
    }
    */
    tabs[current]->context->open();
    tabs[current]->active = true;
}

void TabbedBox::up(){
    if (tabs.size() == 0){
        return;
    }
    if (!inTab){
        moveTab(-1);
    } else {
        tabs[current]->context->previous();
    }
}

void TabbedBox::down(){
    if (tabs.size() == 0){
        return;
    }
    if (!inTab){
        moveTab(1);
    } else {
        tabs[current]->context->next();
    }
}

void TabbedBox::left(){
    if (tabs.size() == 0){
        return;
    }
    if (!inTab){
        moveTab(-1);
    } else {
        tabs[current]->context->adjustLeft();
    }
}

void TabbedBox::right(){
    if (tabs.size() == 0){
        return;
    }
    if (!inTab){
        moveTab(1);
    } else {
        tabs[current]->context->adjustRight();
    }
}

void TabbedBox::toggleTabSelect(){
    inTab = !inTab;
}

unsigned int TabbedBox::getCurrentIndex() const {
    if (tabs.size() == 0){
        return 0;
    }
    return this->tabs[current]->context->getCurrentIndex();
}

void TabbedBox::setTabFontColor(int color){
    tabFontColor = color;
    if (activeTabFontColor){
	delete activeTabFontColor;
    }
    activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}

void TabbedBox::setSelectedTabFontColor(int color){
    currentTabFontColor = color;
    if (activeTabFontColor){
	delete activeTabFontColor;
    }
    activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}

void TabbedBox::renderTabs(const Bitmap & bmp){
    const int tabHeight = fontHeight + 5;
    const Font & vFont = Font::getFont(font, fontWidth, fontHeight);

    int x = 0;
    Bitmap::transBlender(0, 0, 0, colors.bodyAlpha);

    for (std::vector<Gui::Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
        Gui::Tab * tab = *i;
        const int textWidth = vFont.textLength(tab->name.c_str()) + 5;
	// for last tab
	int modifier = 0;
	// Check last tab so we can ensure proper sizing
	if ( i == (tabs.begin() + tabs.size() -1)){
	    if ( ( (tabWidthMax * (tabs.size() - 1) ) + textWidth ) != (unsigned int)location.getWidth() ){
		modifier = location.getWidth() - x - (tab->active ? textWidth : tabWidthMax);
	    }
	}

	if (tab->context->location.getRadius() > 0){
        } else {
            if (tab->active){
		if (!inTab){
		    //bmp.translucent().rectangle(x, 0, x+textWidth + modifier - 1, tabHeight, colors.border);
		    bmp.translucent().vLine(0,x,tabHeight,colors.border);
		    bmp.translucent().hLine(x,0,x+textWidth+modifier-1,colors.border);
		    bmp.translucent().vLine(0,x+textWidth+modifier-1,tabHeight,colors.border);
		    bmp.translucent().rectangleFill( x+1, 1, x+textWidth + modifier - 2, tabHeight, colors.body);

		    bmp.setClipRect(x, 0, x+textWidth + modifier, tabHeight-1);
		    vFont.printf(x + (((textWidth + modifier)/2)-(((textWidth + modifier) - 5)/2)), 0, currentTabFontColor, bmp, tab->name, 0 );
		} else {
		    //bmp.translucent().rectangle(x, 0, x+textWidth + modifier -1, tabHeight, colors.border);
		    bmp.translucent().vLine(0,x,tabHeight,colors.border);
		    bmp.translucent().hLine(x,0,x+textWidth+modifier-1,colors.border);
		    bmp.translucent().vLine(0,x+textWidth+modifier-1,tabHeight,colors.border);
		    bmp.translucent().rectangleFill( x+1, 1, x+textWidth-2 + modifier, tabHeight, colors.body );

		    bmp.setClipRect(x, 0, x+textWidth + modifier, tabHeight-1);
		    vFont.printf(x + (((textWidth + modifier)/2)-(((textWidth + modifier) - 5)/2)), 0, activeTabFontColor->current(), bmp, tab->name, 0 );
		}

		x+=textWidth + modifier;
            } else {
		const int heightMod = tabHeight * .15;
		bmp.translucent().rectangle(x, 1 + heightMod, x+tabWidthMax + modifier -1, tabHeight, tabColors.border);
		bmp.translucent().hLine(x,tabHeight,x+tabWidthMax+modifier-1,colors.border);
		bmp.translucent().rectangleFill( x+1, 2 + heightMod, x+tabWidthMax + modifier -2, tabHeight-2, tabColors.body);

		bmp.setClipRect(x+2, 6 + heightMod, x+tabWidthMax + modifier -3, tabHeight-1);
		vFont.printf(x + (((tabWidthMax + modifier)/2)-((textWidth + modifier)/2)), 0, tabFontColor, bmp, tab->name, 0 );
		x += tabWidthMax + modifier;
            }
	    bmp.setClipRect(0, 0, bmp.getWidth(), bmp.getHeight());
        }
    }
}
<commit_msg>Cast to int.<commit_after>#include "util/bitmap.h"
#include "util/trans-bitmap.h"
#include "tabbed-box.h"

#include "menu/menu.h"

#include "util/font.h"

#include "gui/context-box.h"

using namespace Gui;

#if 0
/* FIXME add rounded tabs */
static void roundTab( const Bitmap & work, int radius, int x1, int y1, int x2, int y2, int color, bool bottom = true ){
    const int width = x2 - x1;
    const int height = y2 - y1;
    radius = Mid(0, radius, Min((x1+width - x1)/2, (y1+height - y1)/2));

    work.circleFill(x1+radius, y1+radius, radius, color);
    work.circleFill((x1+width)-radius, y1+radius, radius, color);
    work.circleFill(x1+radius, (y1+height)-radius, radius, color);
    work.circleFill((x1+width)-radius, (y1+height)-radius, radius, color);
    work.rectangleFill( x1+radius, y1, x2-radius, y1+radius, color);
    work.rectangleFill( x1, y1+radius, x2, y2-radius, color);
    work.rectangleFill( x1+radius, y2-radius, x2-radius, y2, color);

    work.line(x1+radius, y1, x1+width-radius, y1, color);
    work.line(x1+radius, y1+height, x1+width-radius,y1+height, color);
    work.line(x1, y1+radius,x1, y1+height-radius, color);
    work.line(x1+width, y1+radius,x1+width, y1+height-radius, color);

    arc(work, x1+radius, y1+radius, S_PI-1.115, radius, color);
    arc(work, x1+radius + (width - radius *2), y1+radius, -S_PI/2 +0.116, radius, color);
    arc(work, x1+width-radius, y1+height-radius, -0.110, radius ,color);
    arc(work, x1+radius, y1+height-radius, S_PI/2-0.119, radius, color);
}
#endif

Tab::Tab():
context(new ContextBox()),
active(false){
    // Set alpha to 0 as we are not interested in the box
    context->colors.borderAlpha = 0;
    context->colors.bodyAlpha = 0;
}

Tab::~Tab(){
    delete context;
}

TabbedBox::TabbedBox():
current(0),
fontWidth(24),
fontHeight(24),
inTab(false),
tabWidthMax(0),
tabFontColor(Bitmap::makeColor(255,255,255)),
currentTabFontColor(Bitmap::makeColor(0,0,255)){
    activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}

TabbedBox::TabbedBox(const TabbedBox & b):
activeTabFontColor(NULL){
    this->location = b.location;
    this->workArea = b.workArea;
}

TabbedBox::~TabbedBox(){
    for (std::vector<Gui::Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
        Gui::Tab * tab = *i;
        if (tab){
            delete tab;
        }
    }

    if (activeTabFontColor){
	delete activeTabFontColor;
    }
}

TabbedBox &TabbedBox::operator=( const TabbedBox &copy){
    location = copy.location;
    workArea = copy.workArea;

    return *this;
}

// Logic
void TabbedBox::act(){
    if (!tabs.empty()){
	const Font & vFont = Font::getFont(font, fontWidth, fontHeight);
	//tabWidthMax = location.getWidth()/tabs.size();
	const int width = vFont.textLength(tabs[current]->name.c_str()) + 5;
	tabWidthMax = (location.getWidth() - width) / (tabs.size() - 1);
    } else {
	return;
    }
    if (!tabs[current]->active){
	tabs[current]->active = true;
    }
    tabs[current]->context->act();
    if (inTab){
	if (activeTabFontColor){
	    activeTabFontColor->update();
	}
    }
}

// Render
void TabbedBox::render(const Bitmap & work){
    const int tabHeight = fontHeight + 5;
    // checkWorkArea();
    Bitmap area(work, location.getX(), location.getY(), location.getWidth(), location.getHeight());
    // Check if we are using a rounded box
    if (location.getRadius() > 0){
        //roundRectFill( *workArea, (int)location.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.body );
        //roundRect( *workArea, (int)location.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.border );
    } else {
        area.translucent().rectangleFill(0, tabHeight+1, location.getWidth()-1, location.getHeight()-1, colors.body );
        //area.translucent().rectangle(0, tabHeight, location.getWidth()-1, location.getHeight()-1, colors.border );
	area.translucent().vLine(tabHeight,0,location.getHeight()-1,colors.border);
	area.translucent().hLine(0,location.getHeight()-1,location.getWidth()-1,colors.border);
	area.translucent().vLine(tabHeight,location.getWidth()-1,location.getHeight()-1,colors.border);
    }

    tabs[current]->context->render(area);

    renderTabs(area);

    /* FIXME: only render the background in translucent mode, the text should
     * not be translucent
     */
    // workArea->draw(location.getX(), location.getY(), work);
}

// Add tab
void TabbedBox::addTab(const std::string & name, const std::vector<ContextItem *> & list){
    for (std::vector<Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
	Tab * tab = *i;
	if (tab->name == name){
	    return;
	}
    }
    Tab * tab = new Tab();
    tab->name = name;
    tab->context->setList(list);
    tab->context->setFont(font, fontWidth, fontHeight);
    const int modifier = fontHeight * .35;
    tab->context->location.setPosition(Gui::AbsolutePoint(0, fontHeight + modifier));
    tab->context->location.setPosition2(Gui::AbsolutePoint(location.getWidth(), location.getHeight()- modifier));
    tab->context->open();
    tabs.push_back(tab);
}

void TabbedBox::moveTab(int direction){
    tabs[current]->context->close();
    tabs[current]->active = false;
    current = ((int)current + direction + tabs.size()) % tabs.size();
    /*
    if (current == 0){
        current = tabs.size()-1;
    } else {
        current--;
    }
    */
    tabs[current]->context->open();
    tabs[current]->active = true;
}

void TabbedBox::up(){
    if (tabs.size() == 0){
        return;
    }
    if (!inTab){
        moveTab(-1);
    } else {
        tabs[current]->context->previous();
    }
}

void TabbedBox::down(){
    if (tabs.size() == 0){
        return;
    }
    if (!inTab){
        moveTab(1);
    } else {
        tabs[current]->context->next();
    }
}

void TabbedBox::left(){
    if (tabs.size() == 0){
        return;
    }
    if (!inTab){
        moveTab(-1);
    } else {
        tabs[current]->context->adjustLeft();
    }
}

void TabbedBox::right(){
    if (tabs.size() == 0){
        return;
    }
    if (!inTab){
        moveTab(1);
    } else {
        tabs[current]->context->adjustRight();
    }
}

void TabbedBox::toggleTabSelect(){
    inTab = !inTab;
}

unsigned int TabbedBox::getCurrentIndex() const {
    if (tabs.size() == 0){
        return 0;
    }
    return this->tabs[current]->context->getCurrentIndex();
}

void TabbedBox::setTabFontColor(int color){
    tabFontColor = color;
    if (activeTabFontColor){
	delete activeTabFontColor;
    }
    activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}

void TabbedBox::setSelectedTabFontColor(int color){
    currentTabFontColor = color;
    if (activeTabFontColor){
	delete activeTabFontColor;
    }
    activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}

void TabbedBox::renderTabs(const Bitmap & bmp){
    const int tabHeight = fontHeight + 5;
    const Font & vFont = Font::getFont(font, fontWidth, fontHeight);

    int x = 0;
    Bitmap::transBlender(0, 0, 0, colors.bodyAlpha);

    for (std::vector<Gui::Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
        Gui::Tab * tab = *i;
        const int textWidth = vFont.textLength(tab->name.c_str()) + 5;
	// for last tab
	int modifier = 0;
	// Check last tab so we can ensure proper sizing
	if ( i == (tabs.begin() + tabs.size() -1)){
	    if ( ( (tabWidthMax * (tabs.size() - 1) ) + textWidth ) != (unsigned int)location.getWidth() ){
		modifier = location.getWidth() - x - (tab->active ? textWidth : tabWidthMax);
	    }
	}

	if (tab->context->location.getRadius() > 0){
        } else {
            if (tab->active){
		if (!inTab){
		    //bmp.translucent().rectangle(x, 0, x+textWidth + modifier - 1, tabHeight, colors.border);
		    bmp.translucent().vLine(0,x,tabHeight,colors.border);
		    bmp.translucent().hLine(x,0,x+textWidth+modifier-1,colors.border);
		    bmp.translucent().vLine(0,x+textWidth+modifier-1,tabHeight,colors.border);
		    bmp.translucent().rectangleFill( x+1, 1, x+textWidth + modifier - 2, tabHeight, colors.body);

		    bmp.setClipRect(x, 0, x+textWidth + modifier, tabHeight-1);
		    vFont.printf(x + (((textWidth + modifier)/2)-(((textWidth + modifier) - 5)/2)), 0, currentTabFontColor, bmp, tab->name, 0 );
		} else {
		    //bmp.translucent().rectangle(x, 0, x+textWidth + modifier -1, tabHeight, colors.border);
		    bmp.translucent().vLine(0,x,tabHeight,colors.border);
		    bmp.translucent().hLine(x,0,x+textWidth+modifier-1,colors.border);
		    bmp.translucent().vLine(0,x+textWidth+modifier-1,tabHeight,colors.border);
		    bmp.translucent().rectangleFill( x+1, 1, x+textWidth-2 + modifier, tabHeight, colors.body );

		    bmp.setClipRect(x, 0, x+textWidth + modifier, tabHeight-1);
		    vFont.printf(x + (((textWidth + modifier)/2)-(((textWidth + modifier) - 5)/2)), 0, activeTabFontColor->current(), bmp, tab->name, 0 );
		}

		x+=textWidth + modifier;
            } else {
		const int heightMod = tabHeight * .15;
		bmp.translucent().rectangle(x, 1 + heightMod, x+tabWidthMax + modifier -1, tabHeight, tabColors.border);
		bmp.translucent().hLine(x,tabHeight,x+tabWidthMax+modifier-1,colors.border);
		bmp.translucent().rectangleFill( x+1, 2 + heightMod, x+tabWidthMax + modifier -2, tabHeight-2, tabColors.body);

		bmp.setClipRect(x+2, 6 + heightMod, x+tabWidthMax + modifier -3, tabHeight-1);
		vFont.printf(x + (((tabWidthMax + modifier)/2)-((textWidth + modifier)/2)), 0, tabFontColor, bmp, tab->name, 0 );
		x += tabWidthMax + modifier;
            }
	    bmp.setClipRect(0, 0, bmp.getWidth(), bmp.getHeight());
        }
    }
}
<|endoftext|>


<commit_before>#include "client.h"
#include "gconsole.h"
#include "net_worm.h"
#include "particle.h"
#include "part_type.h"
#include "game/WormInputHandler.h"
#include "gusgame.h"
#include "network.h"
#include "player_options.h"
#include "encoding.h"
#include <memory>
#include "util/log.h"

#include "netstream.h"

Client::Client() : Net_Control(false)
{
	Net_setControlID(0);
	Net_setDebugName("Net_CLI");
}

void Client::Net_cbConnectResult(eNet_ConnectResult res) {
	if(res != eNet_ConnAccepted) {
		errors << "Client::Net_cbConnectResult: connection not accepted" << endl;
		return;
	}

	console.addLogMsg("* CONNECTION ACCEPTED");
	network.incConnCount();

	// earlier, we did the mod/level loading here
	// _reply contained two strings, containing level/mod name
	sendConsistencyInfo();
	Net_requestNetMode(NetConnID_server(), 1);
}

Client::~Client()
{
}

void Client::sendConsistencyInfo()
{
	std::auto_ptr<Net_BitStream> req(new Net_BitStream);
	req->addInt(Network::ConsistencyInfo, 8);
	req->addInt(Network::protocolVersion, 32);
	gusGame.addCRCs(req.get());
	Net_sendData( network.getServerID(), req.release(), eNet_ReliableOrdered );
}

void Client::Net_cbConnectionClosed(Net_ConnID _id, eNet_CloseReason _reason, Net_BitStream &_reasondata)
{
	network.decConnCount();
	switch( _reason )
	{
		case eNet_ClosedDisconnect:
		{
			Network::DConnEvents dcEvent = static_cast<Network::DConnEvents>( _reasondata.getInt(8) );
			switch( dcEvent )
			{
				case Network::ServerMapChange:
				{
					console.addLogMsg("* SERVER CHANGED MAP");
					network.olxReconnect(150);
					gusGame.reset(GusGame::ServerChangeMap);
				}
				break;
				case Network::Quit:
				{
					console.addLogMsg("* CONNECTION CLOSED BY SERVER");
					gusGame.reset(GusGame::ServerQuit);
				}
				break;
				case Network::Kick:
				{
					console.addLogMsg("* YOU WERE KICKED");
					gusGame.reset(GusGame::Kicked);
				}
				break;
				case Network::IncompatibleData:
				{
					console.addLogMsg("* YOU HAVE INCOMPATIBLE DATA");
					gusGame.reset(GusGame::IncompatibleData);
				}
				break;

				case Network::IncompatibleProtocol:
				{
					console.addLogMsg("* THE HOST RUNS AN INCOMPATIBLE VERSION OF VERMES");
					gusGame.reset(GusGame::IncompatibleProtocol);
				}
				break;

				default:
				{
					console.addLogMsg("* CONNECTION CLOSED BY DUNNO WHAT :O");
					gusGame.reset(GusGame::ServerQuit);
				}
				break;
			}
		}
		break;

		case eNet_ClosedTimeout:
			console.addLogMsg("* CONNECTION TIMEDOUT");
			gusGame.reset(GusGame::ServerQuit);
		break;

		case eNet_ClosedReconnect:
			console.addLogMsg("* CONNECTION RECONNECTED");
		break;

		default:
		break;
	}

	DLOG("A connection was closed");
}

void Client::Net_cbDataReceived( Net_ConnID id, Net_BitStream& data)
{
	int event = Encoding::decode(data, Network::ClientEvents::Max);
	switch(event)
	{
		case Network::ClientEvents::LuaEvents:
		{
			for(int t = Network::LuaEventGroup::GusGame;
				t < Network::LuaEventGroup::Max; ++t)
			{
				int c = data.getInt(8);
				for(int i = 0; i < c; ++i)
				{
					std::string name = data.getString();
					network.indexLuaEvent((Network::LuaEventGroup::type)t, name);
				}
			}
		}
		break;
	}
}

void Client::Net_cbNodeRequest_Dynamic( Net_ConnID _id, Net_ClassID _requested_class, Net_BitStream *_announcedata, eNet_NodeRole _role, Net_NodeID _net_id )
{
	// check the requested class
	if ( _requested_class == CWorm::classID )
	{
		if(_announcedata == NULL) {
			warnings << "Net_cbNodeRequest_Dynamic for CWorm without announce data" << endl;
			return;
		}

		int wormid = _announcedata->getInt(8);
		if(wormid < 0 || wormid >= MAX_WORMS) {
			warnings << "Net_cbNodeRequest_Dynamic for CWorm: wormid " << wormid << " invalid" << endl;
			return;
		}

		notes << "Net_cbNodeRequest_Dynamic for worm " << wormid << ", nodeid " << _net_id << endl;

		CWorm* worm = &cClient->getRemoteWorms()[wormid];
		if(!worm->isUsed()) {
			warnings << "Net_cbNodeRequest_Dynamic for CWorm: worm " << wormid << " is not used" << endl;
			return;
		}

		worm->NetWorm_Init(false);
	}else if ( _requested_class == CWormInputHandler::classID )
	{
		if(_announcedata == NULL) {
			warnings << "Net_cbNodeRequest_Dynamic for CWormInputHandler without announce data" << endl;
			return;
		}

		int wormid = _announcedata->getInt(8);
		if(wormid < 0 || wormid >= MAX_WORMS) {
			warnings << "Net_cbNodeRequest_Dynamic for CWormInputHandler: wormid " << wormid << " invalid" << endl;
			return;
		}

		CWorm* worm = &cClient->getRemoteWorms()[wormid];
		if(!worm->isUsed()) {
			warnings << "Net_cbNodeRequest_Dynamic for CWormInputHandler: worm " << wormid << " is not used" << endl;
			return;
		}

		notes << "Net_cbNodeRequest_Dynamic: new player (node " << _net_id << ") for worm " << wormid << ", set to " << ((_role == eNet_RoleOwner) ? "owner" : "proxy") << endl;

		// Creates a player class depending on the role
		CWormInputHandler* player = gusGame.addPlayer ( (_role == eNet_RoleOwner) ? GusGame::OWNER : GusGame::PROXY, worm );
		player->assignNetworkRole(false);

		if(worm->m_inputHandler) {
			warnings << "Net_cbNodeRequest_Dynamic: worm " << worm->getName() << " has already the following input handler set: "; warnings.flush();
			warnings << worm->m_inputHandler->name() << endl;
			worm->m_inputHandler->quit();
			worm->m_inputHandler = NULL;
		}

		worm->m_inputHandler = player;

		cClient->SetupGameInputs(); // we must init the inputs for the new inputhandler

		if(cClient->getGameReady()) {
			if(cClient->getStatus() == NET_PLAYING) // playing
				player->startGame();
			// Dont do that right now, no wpn selection in gus
			/* else
				player->initWeaponSelection(); */
		}

	}else if( _requested_class == Particle::classID )
	{
		int typeIndex = Encoding::decode(*_announcedata, partTypeList.size());
		CWormInputHandler* owner = gusGame.findPlayerWithID(_announcedata->getInt(32));
		newParticle_requested(partTypeList[typeIndex], Vec(), Vec(), 1, owner, Angle());
	}else
	{
		console.addLogMsg("* ERROR: INVALID DYNAMIC NODE REQUEST");
	}

}

<commit_msg>init wpn selection for lx<commit_after>#include "client.h"
#include "gconsole.h"
#include "net_worm.h"
#include "particle.h"
#include "part_type.h"
#include "game/WormInputHandler.h"
#include "gusgame.h"
#include "network.h"
#include "player_options.h"
#include "encoding.h"
#include <memory>
#include "util/log.h"

#include "netstream.h"
#include "game/Game.h"
#include "CGameScript.h"

Client::Client() : Net_Control(false)
{
	Net_setControlID(0);
	Net_setDebugName("Net_CLI");
}

void Client::Net_cbConnectResult(eNet_ConnectResult res) {
	if(res != eNet_ConnAccepted) {
		errors << "Client::Net_cbConnectResult: connection not accepted" << endl;
		return;
	}

	console.addLogMsg("* CONNECTION ACCEPTED");
	network.incConnCount();

	// earlier, we did the mod/level loading here
	// _reply contained two strings, containing level/mod name
	sendConsistencyInfo();
	Net_requestNetMode(NetConnID_server(), 1);
}

Client::~Client()
{
}

void Client::sendConsistencyInfo()
{
	std::auto_ptr<Net_BitStream> req(new Net_BitStream);
	req->addInt(Network::ConsistencyInfo, 8);
	req->addInt(Network::protocolVersion, 32);
	gusGame.addCRCs(req.get());
	Net_sendData( network.getServerID(), req.release(), eNet_ReliableOrdered );
}

void Client::Net_cbConnectionClosed(Net_ConnID _id, eNet_CloseReason _reason, Net_BitStream &_reasondata)
{
	network.decConnCount();
	switch( _reason )
	{
		case eNet_ClosedDisconnect:
		{
			Network::DConnEvents dcEvent = static_cast<Network::DConnEvents>( _reasondata.getInt(8) );
			switch( dcEvent )
			{
				case Network::ServerMapChange:
				{
					console.addLogMsg("* SERVER CHANGED MAP");
					network.olxReconnect(150);
					gusGame.reset(GusGame::ServerChangeMap);
				}
				break;
				case Network::Quit:
				{
					console.addLogMsg("* CONNECTION CLOSED BY SERVER");
					gusGame.reset(GusGame::ServerQuit);
				}
				break;
				case Network::Kick:
				{
					console.addLogMsg("* YOU WERE KICKED");
					gusGame.reset(GusGame::Kicked);
				}
				break;
				case Network::IncompatibleData:
				{
					console.addLogMsg("* YOU HAVE INCOMPATIBLE DATA");
					gusGame.reset(GusGame::IncompatibleData);
				}
				break;

				case Network::IncompatibleProtocol:
				{
					console.addLogMsg("* THE HOST RUNS AN INCOMPATIBLE VERSION OF VERMES");
					gusGame.reset(GusGame::IncompatibleProtocol);
				}
				break;

				default:
				{
					console.addLogMsg("* CONNECTION CLOSED BY DUNNO WHAT :O");
					gusGame.reset(GusGame::ServerQuit);
				}
				break;
			}
		}
		break;

		case eNet_ClosedTimeout:
			console.addLogMsg("* CONNECTION TIMEDOUT");
			gusGame.reset(GusGame::ServerQuit);
		break;

		case eNet_ClosedReconnect:
			console.addLogMsg("* CONNECTION RECONNECTED");
		break;

		default:
		break;
	}

	DLOG("A connection was closed");
}

void Client::Net_cbDataReceived( Net_ConnID id, Net_BitStream& data)
{
	int event = Encoding::decode(data, Network::ClientEvents::Max);
	switch(event)
	{
		case Network::ClientEvents::LuaEvents:
		{
			for(int t = Network::LuaEventGroup::GusGame;
				t < Network::LuaEventGroup::Max; ++t)
			{
				int c = data.getInt(8);
				for(int i = 0; i < c; ++i)
				{
					std::string name = data.getString();
					network.indexLuaEvent((Network::LuaEventGroup::type)t, name);
				}
			}
		}
		break;
	}
}

void Client::Net_cbNodeRequest_Dynamic( Net_ConnID _id, Net_ClassID _requested_class, Net_BitStream *_announcedata, eNet_NodeRole _role, Net_NodeID _net_id )
{
	// check the requested class
	if ( _requested_class == CWorm::classID )
	{
		if(_announcedata == NULL) {
			warnings << "Net_cbNodeRequest_Dynamic for CWorm without announce data" << endl;
			return;
		}

		int wormid = _announcedata->getInt(8);
		if(wormid < 0 || wormid >= MAX_WORMS) {
			warnings << "Net_cbNodeRequest_Dynamic for CWorm: wormid " << wormid << " invalid" << endl;
			return;
		}

		notes << "Net_cbNodeRequest_Dynamic for worm " << wormid << ", nodeid " << _net_id << endl;

		CWorm* worm = &cClient->getRemoteWorms()[wormid];
		if(!worm->isUsed()) {
			warnings << "Net_cbNodeRequest_Dynamic for CWorm: worm " << wormid << " is not used" << endl;
			return;
		}

		worm->NetWorm_Init(false);
	}else if ( _requested_class == CWormInputHandler::classID )
	{
		if(_announcedata == NULL) {
			warnings << "Net_cbNodeRequest_Dynamic for CWormInputHandler without announce data" << endl;
			return;
		}

		int wormid = _announcedata->getInt(8);
		if(wormid < 0 || wormid >= MAX_WORMS) {
			warnings << "Net_cbNodeRequest_Dynamic for CWormInputHandler: wormid " << wormid << " invalid" << endl;
			return;
		}

		CWorm* worm = &cClient->getRemoteWorms()[wormid];
		if(!worm->isUsed()) {
			warnings << "Net_cbNodeRequest_Dynamic for CWormInputHandler: worm " << wormid << " is not used" << endl;
			return;
		}

		notes << "Net_cbNodeRequest_Dynamic: new player (node " << _net_id << ") for worm " << wormid << ", set to " << ((_role == eNet_RoleOwner) ? "owner" : "proxy") << endl;

		// Creates a player class depending on the role
		CWormInputHandler* player = gusGame.addPlayer ( (_role == eNet_RoleOwner) ? GusGame::OWNER : GusGame::PROXY, worm );
		player->assignNetworkRole(false);

		if(worm->m_inputHandler) {
			warnings << "Net_cbNodeRequest_Dynamic: worm " << worm->getName() << " has already the following input handler set: "; warnings.flush();
			warnings << worm->m_inputHandler->name() << endl;
			worm->m_inputHandler->quit();
			worm->m_inputHandler = NULL;
		}

		worm->m_inputHandler = player;

		cClient->SetupGameInputs(); // we must init the inputs for the new inputhandler

		if(cClient->getGameReady()) {
			if(cClient->getStatus() == NET_PLAYING) // playing
				player->startGame();
			else if(!game.gameScript()->gusEngineUsed())
				player->initWeaponSelection();
		}

	}else if( _requested_class == Particle::classID )
	{
		int typeIndex = Encoding::decode(*_announcedata, partTypeList.size());
		CWormInputHandler* owner = gusGame.findPlayerWithID(_announcedata->getInt(32));
		newParticle_requested(partTypeList[typeIndex], Vec(), Vec(), 1, owner, Angle());
	}else
	{
		console.addLogMsg("* ERROR: INVALID DYNAMIC NODE REQUEST");
	}

}

<|endoftext|>


<commit_before>/*
Copyright (c) 2015 Daniel Selsam. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Daniel Selsam
*/
#include "kernel/instantiate.h"
#include "kernel/abstract.h"
#include "kernel/inductive/inductive.h"
#include "library/blast/blast.h"
#include "library/blast/action_result.h"
#include "library/blast/forward/forward_actions.h"
#include "library/blast/proof_expr.h"
#include "library/blast/choice_point.h"
#include "library/blast/hypothesis.h"
#include "library/blast/util.h"
#include "library/expr_lt.h"
#include "library/head_map.h"

namespace lean {
namespace blast {

action_result qfc_action(list<gexpr> const & lemmas) {
    return action_result::failed();
}

}}
<commit_msg>fix(library/blast/forward/qcf): compilation warning<commit_after>/*
Copyright (c) 2015 Daniel Selsam. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Daniel Selsam
*/
#include "kernel/instantiate.h"
#include "kernel/abstract.h"
#include "kernel/inductive/inductive.h"
#include "library/blast/blast.h"
#include "library/blast/action_result.h"
#include "library/blast/forward/forward_actions.h"
#include "library/blast/proof_expr.h"
#include "library/blast/choice_point.h"
#include "library/blast/hypothesis.h"
#include "library/blast/util.h"
#include "library/expr_lt.h"
#include "library/head_map.h"

namespace lean {
namespace blast {

action_result qfc_action(list<gexpr> const &) {
    return action_result::failed();
}

}}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "itkJSONImageIO.h"

#include "itkMetaDataObject.h"
#include "itkIOCommon.h"

#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/ostreamwrapper.h"

namespace itk
{

JSONImageIO
::JSONImageIO()
{
  this->SetNumberOfDimensions(3);
  this->AddSupportedWriteExtension(".json");
  this->AddSupportedReadExtension(".json");
}

JSONImageIO
::~JSONImageIO()
{
}

bool
JSONImageIO
::SupportsDimension(unsigned long itkNotUsed(dimension))
{
  return true;
}

void
JSONImageIO
::PrintSelf(std::ostream & os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
}

ImageIOBase::IOComponentType
JSONImageIO
::JSToITKComponentType(const std::string & jsComponentType)
{
  if( jsComponentType == "int8_t" )
    {
    return CHAR;
    }
  else if( jsComponentType == "uint8_t" )
    {
    return UCHAR;
    }
  else if( jsComponentType == "int16_t" )
    {
    return SHORT;
    }
  else if( jsComponentType == "uint16_t" )
    {
    return USHORT;
    }
  else if( jsComponentType == "int32_t" )
    {
    return INT;
    }
  else if( jsComponentType == "uint32_t" )
    {
    return UINT;
    }
  else if( jsComponentType == "int64_t" )
    {
    return LONGLONG;
    }
  else if( jsComponentType == "uint64_t" )
    {
    return ULONGLONG;
    }
  else if( jsComponentType == "float" )
    {
    return FLOAT;
    }
  else if( jsComponentType == "double" )
    {
    return DOUBLE;
    }
  return UNKNOWNCOMPONENTTYPE;
}

std::string
JSONImageIO
::ITKToJSComponentType(const ImageIOBase::IOComponentType itkComponentType)
{
  switch ( itkComponentType )
    {
    case CHAR:
      return "int8_t";

    case UCHAR:
      return "uint8_t";

    case SHORT:
      return "int16_t";

    case USHORT:
      return "uint16_t";;

    case INT:
      return "int32_t";

    case UINT:
      return "uint32_t";;

    case LONG:
      return "int64_t";

    case ULONG:
      return "uint64_t";;

    case LONGLONG:
      return "int64_t";

    case ULONGLONG:
      return "uint64_t";

    case FLOAT:
      return "float";

    case DOUBLE:
      return "double";

    default:
      return "int8_t";
    }
}

ImageIOBase::IOPixelType
JSONImageIO
::JSToITKPixelType( const int jsPixelType )
{
  switch ( jsPixelType )
    {
    case 0:
      return UNKNOWNPIXELTYPE;
    case 1:
      return SCALAR;
    case 2:
      return RGB;
    case 3:
      return RGBA;
    case 4:
      return OFFSET;
    case 5:
      return VECTOR;
    case 6:
      return POINT;
    case 7:
      return COVARIANTVECTOR;
    case 8:
      return SYMMETRICSECONDRANKTENSOR;
    case 9:
      return DIFFUSIONTENSOR3D;
    case 10:
      return COMPLEX;
    case 11:
      return FIXEDARRAY;
    case 13:
      return MATRIX;
    }

  return UNKNOWNPIXELTYPE;
}

int
JSONImageIO
::ITKToJSPixelType( const ImageIOBase::IOPixelType itkPixelType )
{
  switch ( itkPixelType )
    {
    case UNKNOWNPIXELTYPE:
      return 0;
    case SCALAR:
      return 1;
    case RGB:
      return 2;
    case RGBA:
      return 3;
    case OFFSET:
      return 4;
    case VECTOR:
      return 5;
    case POINT:
      return 6;
    case COVARIANTVECTOR:
      return 7;
    case SYMMETRICSECONDRANKTENSOR:
      return 7;
    case DIFFUSIONTENSOR3D:
      return 7;
    case COMPLEX:
      return 10;
    case FIXEDARRAY:
      return 11;
    case MATRIX:
      return 13;
    }

  return 0;
}

bool
JSONImageIO
::CanReadFile(const char *filename)
{
  // Check the extension first to avoid opening files that do not
  // look like nrrds.  The file must have an appropriate extension to be
  // recognized.
  std::string fname = filename;

  bool extensionFound = false;
  std::string::size_type jsonPos = fname.rfind(".json");
  if ( ( jsonPos != std::string::npos )
       && ( jsonPos == fname.length() - 5 ) )
    {
    extensionFound = true;
    }

  if ( !extensionFound )
    {
    itkDebugMacro(<< "The filename extension is not recognized");
    return false;
    }

  std::ifstream inputStream;
  try
    {
    this->OpenFileForReading( inputStream, fname, true );
    }
  catch( ExceptionObject & )
    {
    return false;
    }

  std::string str((std::istreambuf_iterator<char>(inputStream)),
                   std::istreambuf_iterator<char>());
  rapidjson::Document document;
  if( document.Parse( str.c_str() ).HasParseError() )
    {
    inputStream.close();
    return false;
    }

  if( !document.HasMember("imageType") )
    {
    return false;
    }

  inputStream.close();
  return true;
}

void
JSONImageIO
::ReadImageInformation()
{
  this->SetByteOrderToLittleEndian();

  std::ifstream inputStream;
  this->OpenFileForReading( inputStream, this->GetFileName(), true );
  rapidjson::Document document;
  std::string str((std::istreambuf_iterator<char>(inputStream)),
                   std::istreambuf_iterator<char>());
  if (document.Parse(str.c_str()).HasParseError())
    {
    itkExceptionMacro("Could not parse JSON");
    return;
    }

  const rapidjson::Value & imageType = document["imageType"];
  const int dimension = imageType["dimension"].GetInt();
  this->SetNumberOfDimensions( dimension );
  const std::string componentType( imageType["componentType"].GetString() );
  const ImageIOBase::IOComponentType ioComponentType = this->JSToITKComponentType( componentType );
  this->SetComponentType( ioComponentType );
  const int pixelType( imageType["pixelType"].GetInt() );
  const ImageIOBase::IOPixelType ioPixelType = this->JSToITKPixelType( pixelType );
  this->SetPixelType( ioPixelType );
  this->SetNumberOfComponents( imageType["components"].GetInt() );

  const rapidjson::Value & origin = document["origin"];
  int count = 0;
  for( rapidjson::Value::ConstValueIterator itr = origin.Begin(); itr != origin.End(); ++itr )
    {
    this->SetOrigin( count, itr->GetDouble() );
    ++count;
    }

  const rapidjson::Value & spacing = document["spacing"];
  count = 0;
  for( rapidjson::Value::ConstValueIterator itr = spacing.Begin(); itr != spacing.End(); ++itr )
    {
    this->SetSpacing( count, itr->GetDouble() );
    ++count;
    }

  const rapidjson::Value & directionContainer = document["direction"];
  const rapidjson::Value & direction = directionContainer["data"];
  count = 0;
  for( rapidjson::Value::ConstValueIterator itr = direction.Begin(); itr != direction.End(); )
    {
    std::vector< double > direction( dimension );
    for( unsigned int ii = 0; ii < dimension; ++ii )
      {
      direction[ii] = itr->GetDouble();
      ++itr;
      }
    this->SetDirection( count, direction );
    ++count;
    }

  const rapidjson::Value & size = document["size"];
  count = 0;
  for( rapidjson::Value::ConstValueIterator itr = size.Begin(); itr != size.End(); ++itr )
    {
    this->SetDimensions( count, itr->GetInt() );
    ++count;
    }
}

void
JSONImageIO
::Read( void *buffer )
{
  std::ifstream inputStream;
  this->OpenFileForReading( inputStream, this->GetFileName(), true );
  std::string str((std::istreambuf_iterator<char>(inputStream)),
                   std::istreambuf_iterator<char>());
  rapidjson::Document document;
  if ( document.Parse( str.c_str() ).HasParseError())
    {
    itkExceptionMacro("Could not parse JSON");
    return;
    }

  const std::string dataFile( document["data"].GetString() );
  std::ifstream dataStream;
  this->OpenFileForReading( dataStream, dataFile.c_str() );

  const SizeValueType numberOfBytesToBeRead =
    static_cast< SizeValueType >( this->GetImageSizeInBytes() );
  if ( !this->ReadBufferAsBinary( dataStream, buffer, numberOfBytesToBeRead ) )
    {
    itkExceptionMacro(<< "Read failed: Wanted "
                      << numberOfBytesToBeRead
                      << " bytes, but read "
                      << dataStream.gcount() << " bytes.");
    }
}

bool
JSONImageIO
::CanWriteFile(const char *name)
{
  std::string filename = name;

  if( filename == "" )
    {
    return false;
    }

  bool extensionFound = false;
  std::string::size_type jsonPos = filename.rfind(".json");
  if ( ( jsonPos != std::string::npos )
       && ( jsonPos == filename.length() - 5 ) )
    {
    extensionFound = true;
    }

  if ( !extensionFound )
    {
    itkDebugMacro(<< "The filename extension is not recognized");
    return false;
    }

  return true;
}

void
JSONImageIO
::WriteImageInformation()
{
  rapidjson::Document document;
  document.SetObject();
  rapidjson::Document::AllocatorType& allocator = document.GetAllocator();

  rapidjson::Value imageType;
  imageType.SetObject();

  const unsigned int dimension = this->GetNumberOfDimensions();
  imageType.AddMember("dimension", rapidjson::Value(dimension).Move(), allocator );

  const std::string componentString = this->ITKToJSComponentType( this->GetComponentType() );
  rapidjson::Value componentType;
  componentType.SetString( componentString.c_str(), allocator );
  imageType.AddMember("componentType", componentType.Move(), allocator );

  const int pixelType = this->ITKToJSPixelType( this->GetPixelType() );
  imageType.AddMember("pixelType", rapidjson::Value(pixelType).Move(), allocator );

  imageType.AddMember("components", rapidjson::Value( this->GetNumberOfComponents() ).Move(), allocator );

  document.AddMember( "imageType", imageType.Move(), allocator );

  rapidjson::Value origin(rapidjson::kArrayType);
  for( unsigned int ii = 0; ii < dimension; ++ii )
    {
    origin.PushBack(rapidjson::Value().SetDouble(this->GetOrigin( ii )), allocator);
    }
  document.AddMember( "origin", origin.Move(), allocator );

  rapidjson::Value spacing(rapidjson::kArrayType);
  for( unsigned int ii = 0; ii < dimension; ++ii )
    {
    spacing.PushBack(rapidjson::Value().SetDouble(this->GetSpacing( ii )), allocator);
    }
  document.AddMember( "spacing", spacing.Move(), allocator );

  rapidjson::Value direction(rapidjson::kArrayType);
  for( unsigned int ii = 0; ii < dimension; ++ii )
    {
    const std::vector< double > dimensionDirection = this->GetDirection( ii );
    for( unsigned int jj = 0; jj < dimension; ++jj )
      {
      direction.PushBack(rapidjson::Value().SetDouble( dimensionDirection[jj] ), allocator);
      }
    }
  document.AddMember( "direction", direction.Move(), allocator );

  rapidjson::Value size(rapidjson::kArrayType);
  for( unsigned int ii = 0; ii < dimension; ++ii )
    {
    size.PushBack(rapidjson::Value().SetInt( this->GetDimensions( ii ) ), allocator);
    }
  document.AddMember( "size", size.Move(), allocator );

  std::string dataFileString( std::string( this->GetFileName() ) + ".data" );
  rapidjson::Value dataFile;
  dataFile.SetString( dataFileString.c_str(), allocator );
  document.AddMember( "data", dataFile, allocator );

  std::ofstream outputStream;
  this->OpenFileForWriting( outputStream, this->GetFileName(), true, true );
  rapidjson::OStreamWrapper ostreamWrapper( outputStream );
  rapidjson::PrettyWriter< rapidjson::OStreamWrapper > writer( ostreamWrapper );
  document.Accept( writer );
  outputStream.close();
}

void
JSONImageIO
::Write( const void *buffer )
{
  this->WriteImageInformation();
  const std::string fileName = std::string( this->GetFileName() ) + ".data";
  std::ofstream outputStream;
  this->OpenFileForWriting( outputStream, fileName, true, false );
  const SizeValueType numberOfBytes = this->GetImageSizeInBytes();
  outputStream.write(static_cast< const char * >( buffer ), numberOfBytes); \
}

} // end namespace itk
<commit_msg>style(itkJSONImageIO): Fix too many semi-colons KWStyle error<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "itkJSONImageIO.h"

#include "itkMetaDataObject.h"
#include "itkIOCommon.h"

#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/ostreamwrapper.h"

namespace itk
{

JSONImageIO
::JSONImageIO()
{
  this->SetNumberOfDimensions(3);
  this->AddSupportedWriteExtension(".json");
  this->AddSupportedReadExtension(".json");
}

JSONImageIO
::~JSONImageIO()
{
}

bool
JSONImageIO
::SupportsDimension(unsigned long itkNotUsed(dimension))
{
  return true;
}

void
JSONImageIO
::PrintSelf(std::ostream & os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
}

ImageIOBase::IOComponentType
JSONImageIO
::JSToITKComponentType(const std::string & jsComponentType)
{
  if( jsComponentType == "int8_t" )
    {
    return CHAR;
    }
  else if( jsComponentType == "uint8_t" )
    {
    return UCHAR;
    }
  else if( jsComponentType == "int16_t" )
    {
    return SHORT;
    }
  else if( jsComponentType == "uint16_t" )
    {
    return USHORT;
    }
  else if( jsComponentType == "int32_t" )
    {
    return INT;
    }
  else if( jsComponentType == "uint32_t" )
    {
    return UINT;
    }
  else if( jsComponentType == "int64_t" )
    {
    return LONGLONG;
    }
  else if( jsComponentType == "uint64_t" )
    {
    return ULONGLONG;
    }
  else if( jsComponentType == "float" )
    {
    return FLOAT;
    }
  else if( jsComponentType == "double" )
    {
    return DOUBLE;
    }
  return UNKNOWNCOMPONENTTYPE;
}

std::string
JSONImageIO
::ITKToJSComponentType(const ImageIOBase::IOComponentType itkComponentType)
{
  switch ( itkComponentType )
    {
    case CHAR:
      return "int8_t";

    case UCHAR:
      return "uint8_t";

    case SHORT:
      return "int16_t";

    case USHORT:
      return "uint16_t";

    case INT:
      return "int32_t";

    case UINT:
      return "uint32_t";

    case LONG:
      return "int64_t";

    case ULONG:
      return "uint64_t";

    case LONGLONG:
      return "int64_t";

    case ULONGLONG:
      return "uint64_t";

    case FLOAT:
      return "float";

    case DOUBLE:
      return "double";

    default:
      return "int8_t";
    }
}

ImageIOBase::IOPixelType
JSONImageIO
::JSToITKPixelType( const int jsPixelType )
{
  switch ( jsPixelType )
    {
    case 0:
      return UNKNOWNPIXELTYPE;
    case 1:
      return SCALAR;
    case 2:
      return RGB;
    case 3:
      return RGBA;
    case 4:
      return OFFSET;
    case 5:
      return VECTOR;
    case 6:
      return POINT;
    case 7:
      return COVARIANTVECTOR;
    case 8:
      return SYMMETRICSECONDRANKTENSOR;
    case 9:
      return DIFFUSIONTENSOR3D;
    case 10:
      return COMPLEX;
    case 11:
      return FIXEDARRAY;
    case 13:
      return MATRIX;
    }

  return UNKNOWNPIXELTYPE;
}

int
JSONImageIO
::ITKToJSPixelType( const ImageIOBase::IOPixelType itkPixelType )
{
  switch ( itkPixelType )
    {
    case UNKNOWNPIXELTYPE:
      return 0;
    case SCALAR:
      return 1;
    case RGB:
      return 2;
    case RGBA:
      return 3;
    case OFFSET:
      return 4;
    case VECTOR:
      return 5;
    case POINT:
      return 6;
    case COVARIANTVECTOR:
      return 7;
    case SYMMETRICSECONDRANKTENSOR:
      return 7;
    case DIFFUSIONTENSOR3D:
      return 7;
    case COMPLEX:
      return 10;
    case FIXEDARRAY:
      return 11;
    case MATRIX:
      return 13;
    }

  return 0;
}

bool
JSONImageIO
::CanReadFile(const char *filename)
{
  // Check the extension first to avoid opening files that do not
  // look like nrrds.  The file must have an appropriate extension to be
  // recognized.
  std::string fname = filename;

  bool extensionFound = false;
  std::string::size_type jsonPos = fname.rfind(".json");
  if ( ( jsonPos != std::string::npos )
       && ( jsonPos == fname.length() - 5 ) )
    {
    extensionFound = true;
    }

  if ( !extensionFound )
    {
    itkDebugMacro(<< "The filename extension is not recognized");
    return false;
    }

  std::ifstream inputStream;
  try
    {
    this->OpenFileForReading( inputStream, fname, true );
    }
  catch( ExceptionObject & )
    {
    return false;
    }

  std::string str((std::istreambuf_iterator<char>(inputStream)),
                   std::istreambuf_iterator<char>());
  rapidjson::Document document;
  if( document.Parse( str.c_str() ).HasParseError() )
    {
    inputStream.close();
    return false;
    }

  if( !document.HasMember("imageType") )
    {
    return false;
    }

  inputStream.close();
  return true;
}

void
JSONImageIO
::ReadImageInformation()
{
  this->SetByteOrderToLittleEndian();

  std::ifstream inputStream;
  this->OpenFileForReading( inputStream, this->GetFileName(), true );
  rapidjson::Document document;
  std::string str((std::istreambuf_iterator<char>(inputStream)),
                   std::istreambuf_iterator<char>());
  if (document.Parse(str.c_str()).HasParseError())
    {
    itkExceptionMacro("Could not parse JSON");
    return;
    }

  const rapidjson::Value & imageType = document["imageType"];
  const int dimension = imageType["dimension"].GetInt();
  this->SetNumberOfDimensions( dimension );
  const std::string componentType( imageType["componentType"].GetString() );
  const ImageIOBase::IOComponentType ioComponentType = this->JSToITKComponentType( componentType );
  this->SetComponentType( ioComponentType );
  const int pixelType( imageType["pixelType"].GetInt() );
  const ImageIOBase::IOPixelType ioPixelType = this->JSToITKPixelType( pixelType );
  this->SetPixelType( ioPixelType );
  this->SetNumberOfComponents( imageType["components"].GetInt() );

  const rapidjson::Value & origin = document["origin"];
  int count = 0;
  for( rapidjson::Value::ConstValueIterator itr = origin.Begin(); itr != origin.End(); ++itr )
    {
    this->SetOrigin( count, itr->GetDouble() );
    ++count;
    }

  const rapidjson::Value & spacing = document["spacing"];
  count = 0;
  for( rapidjson::Value::ConstValueIterator itr = spacing.Begin(); itr != spacing.End(); ++itr )
    {
    this->SetSpacing( count, itr->GetDouble() );
    ++count;
    }

  const rapidjson::Value & directionContainer = document["direction"];
  const rapidjson::Value & direction = directionContainer["data"];
  count = 0;
  for( rapidjson::Value::ConstValueIterator itr = direction.Begin(); itr != direction.End(); )
    {
    std::vector< double > direction( dimension );
    for( unsigned int ii = 0; ii < dimension; ++ii )
      {
      direction[ii] = itr->GetDouble();
      ++itr;
      }
    this->SetDirection( count, direction );
    ++count;
    }

  const rapidjson::Value & size = document["size"];
  count = 0;
  for( rapidjson::Value::ConstValueIterator itr = size.Begin(); itr != size.End(); ++itr )
    {
    this->SetDimensions( count, itr->GetInt() );
    ++count;
    }
}

void
JSONImageIO
::Read( void *buffer )
{
  std::ifstream inputStream;
  this->OpenFileForReading( inputStream, this->GetFileName(), true );
  std::string str((std::istreambuf_iterator<char>(inputStream)),
                   std::istreambuf_iterator<char>());
  rapidjson::Document document;
  if ( document.Parse( str.c_str() ).HasParseError())
    {
    itkExceptionMacro("Could not parse JSON");
    return;
    }

  const std::string dataFile( document["data"].GetString() );
  std::ifstream dataStream;
  this->OpenFileForReading( dataStream, dataFile.c_str() );

  const SizeValueType numberOfBytesToBeRead =
    static_cast< SizeValueType >( this->GetImageSizeInBytes() );
  if ( !this->ReadBufferAsBinary( dataStream, buffer, numberOfBytesToBeRead ) )
    {
    itkExceptionMacro(<< "Read failed: Wanted "
                      << numberOfBytesToBeRead
                      << " bytes, but read "
                      << dataStream.gcount() << " bytes.");
    }
}

bool
JSONImageIO
::CanWriteFile(const char *name)
{
  std::string filename = name;

  if( filename == "" )
    {
    return false;
    }

  bool extensionFound = false;
  std::string::size_type jsonPos = filename.rfind(".json");
  if ( ( jsonPos != std::string::npos )
       && ( jsonPos == filename.length() - 5 ) )
    {
    extensionFound = true;
    }

  if ( !extensionFound )
    {
    itkDebugMacro(<< "The filename extension is not recognized");
    return false;
    }

  return true;
}

void
JSONImageIO
::WriteImageInformation()
{
  rapidjson::Document document;
  document.SetObject();
  rapidjson::Document::AllocatorType& allocator = document.GetAllocator();

  rapidjson::Value imageType;
  imageType.SetObject();

  const unsigned int dimension = this->GetNumberOfDimensions();
  imageType.AddMember("dimension", rapidjson::Value(dimension).Move(), allocator );

  const std::string componentString = this->ITKToJSComponentType( this->GetComponentType() );
  rapidjson::Value componentType;
  componentType.SetString( componentString.c_str(), allocator );
  imageType.AddMember("componentType", componentType.Move(), allocator );

  const int pixelType = this->ITKToJSPixelType( this->GetPixelType() );
  imageType.AddMember("pixelType", rapidjson::Value(pixelType).Move(), allocator );

  imageType.AddMember("components", rapidjson::Value( this->GetNumberOfComponents() ).Move(), allocator );

  document.AddMember( "imageType", imageType.Move(), allocator );

  rapidjson::Value origin(rapidjson::kArrayType);
  for( unsigned int ii = 0; ii < dimension; ++ii )
    {
    origin.PushBack(rapidjson::Value().SetDouble(this->GetOrigin( ii )), allocator);
    }
  document.AddMember( "origin", origin.Move(), allocator );

  rapidjson::Value spacing(rapidjson::kArrayType);
  for( unsigned int ii = 0; ii < dimension; ++ii )
    {
    spacing.PushBack(rapidjson::Value().SetDouble(this->GetSpacing( ii )), allocator);
    }
  document.AddMember( "spacing", spacing.Move(), allocator );

  rapidjson::Value direction(rapidjson::kArrayType);
  for( unsigned int ii = 0; ii < dimension; ++ii )
    {
    const std::vector< double > dimensionDirection = this->GetDirection( ii );
    for( unsigned int jj = 0; jj < dimension; ++jj )
      {
      direction.PushBack(rapidjson::Value().SetDouble( dimensionDirection[jj] ), allocator);
      }
    }
  document.AddMember( "direction", direction.Move(), allocator );

  rapidjson::Value size(rapidjson::kArrayType);
  for( unsigned int ii = 0; ii < dimension; ++ii )
    {
    size.PushBack(rapidjson::Value().SetInt( this->GetDimensions( ii ) ), allocator);
    }
  document.AddMember( "size", size.Move(), allocator );

  std::string dataFileString( std::string( this->GetFileName() ) + ".data" );
  rapidjson::Value dataFile;
  dataFile.SetString( dataFileString.c_str(), allocator );
  document.AddMember( "data", dataFile, allocator );

  std::ofstream outputStream;
  this->OpenFileForWriting( outputStream, this->GetFileName(), true, true );
  rapidjson::OStreamWrapper ostreamWrapper( outputStream );
  rapidjson::PrettyWriter< rapidjson::OStreamWrapper > writer( ostreamWrapper );
  document.Accept( writer );
  outputStream.close();
}

void
JSONImageIO
::Write( const void *buffer )
{
  this->WriteImageInformation();
  const std::string fileName = std::string( this->GetFileName() ) + ".data";
  std::ofstream outputStream;
  this->OpenFileForWriting( outputStream, fileName, true, false );
  const SizeValueType numberOfBytes = this->GetImageSizeInBytes();
  outputStream.write(static_cast< const char * >( buffer ), numberOfBytes); \
}

} // end namespace itk
<|endoftext|>


<commit_before>#include "utils/tag-loader/tag-loader.h"
#include <QMessageBox>
#include <ui_tag-loader.h>
#include "helpers.h"
#include "models/profile.h"
#include "models/site.h"
#include "tags/tag-database.h"
#include "tools/tag-list-loader.h"

#define MIN_TAG_COUNT 20

TagLoader::TagLoader(Profile *profile, QWidget *parent)
	: QDialog(parent), ui(new Ui::TagLoader), m_profile(profile), m_sites(profile->getSites())
{
	ui->setupUi(this);

	resetOptions();
	ui->widgetProgress->hide();

	resize(size().width(), 0);
}

TagLoader::~TagLoader()
{
	delete ui;
}

void TagLoader::resetOptions()
{
	m_options.clear();

	QStringList keys;
	for (auto it = m_sites.constBegin(); it != m_sites.constEnd(); ++it) {
		Site *site = it.value();
		if (TagListLoader::canLoadTags(site)) {
			m_options.append(it.key());
			keys.append(QString("%1 (%L2 tags)").arg(it.key()).arg(site->tagDatabase()->count()));
		}
	}

	int index = ui->comboSource->currentIndex();
	ui->comboSource->clear();
	ui->comboSource->addItems(keys);
	if (index >= 0) {
		ui->comboSource->setCurrentIndex(index);
	}
}

void TagLoader::cancel()
{
	if (m_loader != nullptr) {
		m_loader->cancel();
	}

	emit rejected();
	close();
	deleteLater();
}

void TagLoader::start()
{
	Site *site = m_sites.value(m_options[ui->comboSource->currentIndex()]);

	// Show progress bar
	ui->buttonStart->setEnabled(false);
	ui->progressBar->setValue(0);
	ui->progressBar->setMinimum(0);
	ui->progressBar->setMaximum(0);
	ui->labelProgress->setText("");
	ui->widgetProgress->show();

	// Start loader
	m_loader = new TagListLoader(m_profile, site, MIN_TAG_COUNT, this);
	connect(m_loader, TagListLoader::progress, ui->labelProgress, &QLabel::setText);
	connect(m_loader, TagListLoader::finished, this, &TagLoader::finishedLoading);
	m_loader->start();
}

void TagLoader::finishedLoading()
{
	// Hide progress bar
	ui->buttonStart->setEnabled(true);
	ui->widgetProgress->hide();
	resize(size().width(), 0);

	// Handle errors
	if (!m_loader->error().isEmpty()) {
		error(this, m_loader->error());
	} else {
		QMessageBox::information(this, tr("Finished"), tr("%n tag(s) loaded", "", m_loader->results().count()));
	}

	// Clean-up
	m_loader->deleteLater();
	m_loader = nullptr;

	resetOptions();
}
<commit_msg>Fix pointer to method syntax in TagLoader class<commit_after>#include "utils/tag-loader/tag-loader.h"
#include <QMessageBox>
#include <ui_tag-loader.h>
#include "helpers.h"
#include "models/profile.h"
#include "models/site.h"
#include "tags/tag-database.h"
#include "tools/tag-list-loader.h"

#define MIN_TAG_COUNT 20

TagLoader::TagLoader(Profile *profile, QWidget *parent)
	: QDialog(parent), ui(new Ui::TagLoader), m_profile(profile), m_sites(profile->getSites())
{
	ui->setupUi(this);

	resetOptions();
	ui->widgetProgress->hide();

	resize(size().width(), 0);
}

TagLoader::~TagLoader()
{
	delete ui;
}

void TagLoader::resetOptions()
{
	m_options.clear();

	QStringList keys;
	for (auto it = m_sites.constBegin(); it != m_sites.constEnd(); ++it) {
		Site *site = it.value();
		if (TagListLoader::canLoadTags(site)) {
			m_options.append(it.key());
			keys.append(QString("%1 (%L2 tags)").arg(it.key()).arg(site->tagDatabase()->count()));
		}
	}

	int index = ui->comboSource->currentIndex();
	ui->comboSource->clear();
	ui->comboSource->addItems(keys);
	if (index >= 0) {
		ui->comboSource->setCurrentIndex(index);
	}
}

void TagLoader::cancel()
{
	if (m_loader != nullptr) {
		m_loader->cancel();
	}

	emit rejected();
	close();
	deleteLater();
}

void TagLoader::start()
{
	Site *site = m_sites.value(m_options[ui->comboSource->currentIndex()]);

	// Show progress bar
	ui->buttonStart->setEnabled(false);
	ui->progressBar->setValue(0);
	ui->progressBar->setMinimum(0);
	ui->progressBar->setMaximum(0);
	ui->labelProgress->setText("");
	ui->widgetProgress->show();

	// Start loader
	m_loader = new TagListLoader(m_profile, site, MIN_TAG_COUNT, this);
	connect(m_loader, &TagListLoader::progress, ui->labelProgress, &QLabel::setText);
	connect(m_loader, &TagListLoader::finished, this, &TagLoader::finishedLoading);
	m_loader->start();
}

void TagLoader::finishedLoading()
{
	// Hide progress bar
	ui->buttonStart->setEnabled(true);
	ui->widgetProgress->hide();
	resize(size().width(), 0);

	// Handle errors
	if (!m_loader->error().isEmpty()) {
		error(this, m_loader->error());
	} else {
		QMessageBox::information(this, tr("Finished"), tr("%n tag(s) loaded", "", m_loader->results().count()));
	}

	// Clean-up
	m_loader->deleteLater();
	m_loader = nullptr;

	resetOptions();
}
<|endoftext|>