<commit_before>#include "Renderer.hpp"
#include <GL/glew.h>
#include <glm/gtc/matrix_transform.hpp>
#include <iostream>
#include <math.h>
#include <memory>
#include <stdlib.h>
#include "ui/DebugText.hpp"
Renderer::Renderer(int width, int height):
  width(width),
  height(height),
  perspective_mat(glm::perspective<float>(45.0f, (float) width/height, 0.5f, 50.0f)),
  point_light_shader(std::make_shared<PointLightShader>()),
  spot_light_shader(std::make_shared<SpotLightShader>()),
  dir_light_shader(std::make_shared<LightShader>()),
  ortho(glm::ortho<float>(-10,10,-10,10,-0,10)),
  depth_bias_mat(
      0.5, 0.0, 0.0, 0.0,
      0.0, 0.5, 0.0, 0.0,
      0.0, 0.0, 0.5, 0.0,
      0.5, 0.5, 0.5, 1.0
      )
{
  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

  lights[point_light_shader];
  lights[spot_light_shader];
  lights[dir_light_shader];
}

void Renderer::set_camera(std::shared_ptr<Camera> camera) {
  this->camera = camera;
}

bool draw_shadow_map = false;
void Renderer::pre_render() {
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  glEnable(GL_CULL_FACE);
  glCullFace(GL_BACK);
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);
  glDepthMask(GL_TRUE);

  glFrontFace(GL_CCW);

  if(shown_light_index != -1 && draw_shadow_map) {
    debug_renderer.render_fbo(light_list[shown_light_index]->shadow_map.depth_tex);
  }
}

void Renderer::render_depth_test(std::vector<RenderObject>& render_list) {
  depth_shader.use_shader();
  for(auto& light: light_list) {
    if(light->casts_shadow()) {
      glViewport(0.0f, 0.0f, (float) light->shadow_map.width, (float) light->shadow_map.height);
      glm::mat4 vp_mat;
      vp_mat *= light->get_projection();
      vp_mat *= light->get_view_mat();

      light->shadow_map.bind();
      glClear(GL_DEPTH_BUFFER_BIT);
      render_scene(vp_mat, render_list);
      light->shadow_map.unbind();
    }
  }
  depth_shader.stop();
  glViewport(0.0f, 0.0f, width, height);
}

void Renderer::render_scene(const glm::mat4& vp_mat, std::vector<RenderObject>& render_list) {
  VertexArray& vertex_format = (*render_list[0].mesh.vertex_array);
  vertex_format.bind();
  for(auto& render_object: render_list) {
    if((*render_object.mesh.vertex_array) != vertex_format) {
      vertex_format.unbind();
      vertex_format = (*render_object.mesh.vertex_array);
      vertex_format.bind();
    }
    const glm::mat4& obj_model_mat = render_object.transform.get_model_matrix();
    depth_shader.set_mvp_mat(vp_mat * obj_model_mat);

    depth_shader.set_mask_sampler(3);
    render_object.bind_mask();

    render_object.render();
  }
}

void Renderer::draw_debug_info(std::vector<RenderObject>& render_list) {
  for(const auto& render_object: render_list) {
    draw_aabb(render_object.aabb);
  }

  for(auto& light_type: lights) {
    for(auto& light: light_type.second) {
      draw_point(light->get_pos());
    }
  }
}

void Renderer::render(std::vector<RenderObject>& render_list) {
  int draw_calls = 0;
  pre_render();
  draw_debug_info(render_list);
  render_depth_test(render_list);

  glDisable(GL_BLEND);
  glBlendFunc(GL_ONE, GL_ONE);
  //foreach type of light
  for(auto& light_type: lights) {
    if(light_type.second.size() == 0) {
      continue;
    }
    std::shared_ptr<LightShader> shader = light_type.first;
    //foreach light instance

    shader->use_shader();
    for(auto& light: light_type.second) {
      if(shown_light_index != -1 && light_list[shown_light_index] != light) {
        continue;
      }
      //Might need static_cast
      shader->set_light(*light);
      //foreach vertex format
      VertexArray& vertex_format = (*render_list[0].mesh.vertex_array);
      vertex_format.bind();
      for(auto& render_object: render_list) {
        if((*render_object.mesh.vertex_array) != vertex_format) {
          vertex_format.unbind();
          vertex_format = (*render_object.mesh.vertex_array);
          vertex_format.bind();
        }
        const glm::mat4& obj_model_mat = render_object.transform.get_model_matrix();

        glm::mat4 mvp_mat = glm::mat4();
        mvp_mat *= perspective_mat;
        mvp_mat *= camera->get_view_mat();
        mvp_mat *= obj_model_mat;
        shader->set_mvp_mat(mvp_mat);
        shader->set_model_mat(obj_model_mat);

        shader->set_eye_pos(camera->pos);
        shader->set_eye_dir(camera->dir);

        shader->set_diffuse_sampler(0);
        render_object.bind_diffuse();

        shader->set_normal_sampler(1);
        render_object.bind_normal();

        shader->set_specular_sampler(2);
        render_object.bind_specular();

        shader->set_mask_sampler(3);
        render_object.bind_mask();

        if(light->casts_shadow()) {
          glm::mat4 depth_mvp_mat = glm::mat4();
          depth_mvp_mat *= light->get_projection();
          depth_mvp_mat *= light->get_view_mat();
          depth_mvp_mat *= obj_model_mat;
          depth_mvp_mat = depth_bias_mat * depth_mvp_mat;
          shader->set_depth_mvp_mat(depth_mvp_mat);

          light->shadow_map.bind_shadowmap(GL_TEXTURE4);
          shader->set_shadow_sampler(4);
        }

        shader->set_material(render_object.mesh.material);
        draw_calls++;
        render_object.render();
      }
      glEnable(GL_BLEND);
    }
  }
  draw_sky();
  DebugText::set_value("draw calls", draw_calls);
}

void Renderer::draw_aabb(const AABB& aabb) {
  glEnable(GL_BLEND);
  glm::mat4 vp_mat = glm::mat4();
  vp_mat *= perspective_mat;
  vp_mat *= camera->get_view_mat();
  debug_renderer.draw_aabb(aabb, vp_mat);
}

void Renderer::draw_lines(const std::vector<std::pair<glm::vec3, glm::vec3>>& lines, const glm::vec3& color) {
  glEnable(GL_BLEND);
  glm::mat4 mvp_mat = glm::mat4();
  mvp_mat *= perspective_mat;
  mvp_mat *= camera->get_view_mat();
  debug_renderer.draw_lines(lines, mvp_mat, color);
}

void Renderer::draw_line(const glm::vec3& from, const glm::vec3& to, const glm::vec3& color) {
  glEnable(GL_BLEND);
  glm::mat4 mvp_mat = glm::mat4();
  mvp_mat *= perspective_mat;
  mvp_mat *= camera->get_view_mat();
  debug_renderer.draw_line(from, to, mvp_mat, color);
}

void Renderer::draw_point(const glm::vec3& pos) {
  glm::mat4 mvp_mat = glm::mat4();
  mvp_mat *= perspective_mat;
  mvp_mat *= camera->get_view_mat();
  debug_renderer.draw_point(pos, mvp_mat);
}

void Renderer::toggle_wireframe() {
  static int mode = 0;
  mode++;
  switch(mode) {
    default:
      glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
      mode = 0;
      break;
    case 1:
      glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
      break;
    case 2:
      glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
      break;
  }
}

void Renderer::add_light(std::shared_ptr<PointLight> point_light) {
  lights[point_light_shader].push_back(point_light);
  light_list.push_back(point_light);
  DebugText::set_value("Num lights", light_count());
}

void Renderer::add_light(std::shared_ptr<SpotLight> spot_light) {
  lights[spot_light_shader].push_back(spot_light);
  light_list.push_back(spot_light);
  DebugText::set_value("Num lights", light_count());
}

void Renderer::add_light(std::shared_ptr<DirLight> dir_light) {
  lights[dir_light_shader].push_back(dir_light);
  light_list.push_back(dir_light);
  DebugText::set_value("Num lights", light_count());
}

void Renderer::show_single_light(int index) {
  last_shown_light_index = fmax(0, shown_light_index);
  index = fmax(-1, fmin(index, light_list.size() - 1));
  std::cout << "Show light " << index << "\n";
  shown_light_index = index;
}

std::shared_ptr<Light> Renderer::get_shown_light() {
  if(shown_light_index == -1) {
    return light_list[last_shown_light_index];
  } else {
    return light_list[shown_light_index];
  }
}

int Renderer::light_count() {
  return light_list.size();
}

void Renderer::set_skybox(RenderObject&& skybox) {
  this->skybox = std::make_unique<RenderObject>(skybox);
}

void Renderer::draw_sky() {
  if(skybox) {
    glDepthFunc(GL_EQUAL);
    glDepthRange(1, 1);
    skybox->transform.set_position(camera->pos);
    sky_shader();
    glm::mat4 mvp_mat = glm::mat4();
    mvp_mat *= perspective_mat;
    mvp_mat *= camera->get_view_mat();
    sky_shader.set_mvp_mat(mvp_mat);
    sky_shader.set_model_mat(skybox->transform.get_model_matrix());
    skybox->mesh.vertex_array->bind();
    skybox->render();
    skybox->mesh.vertex_array->unbind();
    sky_shader.stop();
    glDepthRange(0, 1);
    glDepthFunc(GL_LEQUAL);
  }
}

void Renderer::toggle_shadow_map() {
  draw_shadow_map = !draw_shadow_map;
}

void Renderer::clear_lights() {
  lights.clear();
  light_list.clear();
  DebugText::set_value("Num lights", 0);
}

bool vertex_array_sort(const RenderObject& left, const RenderObject& right) {
  return (*left.mesh.vertex_array) == (*right.mesh.vertex_array);
}

void Renderer::render(World& world) {
  render(world.render_list);
}
<commit_msg>Increased far plane<commit_after>#include "Renderer.hpp"
#include <GL/glew.h>
#include <glm/gtc/matrix_transform.hpp>
#include <iostream>
#include <math.h>
#include <memory>
#include <stdlib.h>
#include "ui/DebugText.hpp"
Renderer::Renderer(int width, int height):
  width(width),
  height(height),
  perspective_mat(glm::perspective<float>(45.0f, (float) width/height, 0.5f, 100.0f)),
  point_light_shader(std::make_shared<PointLightShader>()),
  spot_light_shader(std::make_shared<SpotLightShader>()),
  dir_light_shader(std::make_shared<LightShader>()),
  ortho(glm::ortho<float>(-10,10,-10,10,-0,10)),
  depth_bias_mat(
      0.5, 0.0, 0.0, 0.0,
      0.0, 0.5, 0.0, 0.0,
      0.0, 0.0, 0.5, 0.0,
      0.5, 0.5, 0.5, 1.0
      )
{
  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

  lights[point_light_shader];
  lights[spot_light_shader];
  lights[dir_light_shader];
}

void Renderer::set_camera(std::shared_ptr<Camera> camera) {
  this->camera = camera;
}

bool draw_shadow_map = false;
void Renderer::pre_render() {
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  glEnable(GL_CULL_FACE);
  glCullFace(GL_BACK);
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);
  glDepthMask(GL_TRUE);

  glFrontFace(GL_CCW);

  if(shown_light_index != -1 && draw_shadow_map) {
    debug_renderer.render_fbo(light_list[shown_light_index]->shadow_map.depth_tex);
  }
}

void Renderer::render_depth_test(std::vector<RenderObject>& render_list) {
  depth_shader.use_shader();
  for(auto& light: light_list) {
    if(light->casts_shadow()) {
      glViewport(0.0f, 0.0f, (float) light->shadow_map.width, (float) light->shadow_map.height);
      glm::mat4 vp_mat;
      vp_mat *= light->get_projection();
      vp_mat *= light->get_view_mat();

      light->shadow_map.bind();
      glClear(GL_DEPTH_BUFFER_BIT);
      render_scene(vp_mat, render_list);
      light->shadow_map.unbind();
    }
  }
  depth_shader.stop();
  glViewport(0.0f, 0.0f, width, height);
}

void Renderer::render_scene(const glm::mat4& vp_mat, std::vector<RenderObject>& render_list) {
  VertexArray& vertex_format = (*render_list[0].mesh.vertex_array);
  vertex_format.bind();
  for(auto& render_object: render_list) {
    if((*render_object.mesh.vertex_array) != vertex_format) {
      vertex_format.unbind();
      vertex_format = (*render_object.mesh.vertex_array);
      vertex_format.bind();
    }
    const glm::mat4& obj_model_mat = render_object.transform.get_model_matrix();
    depth_shader.set_mvp_mat(vp_mat * obj_model_mat);

    depth_shader.set_mask_sampler(3);
    render_object.bind_mask();

    render_object.render();
  }
}

void Renderer::draw_debug_info(std::vector<RenderObject>& render_list) {
  for(const auto& render_object: render_list) {
    draw_aabb(render_object.aabb);
  }

  for(auto& light_type: lights) {
    for(auto& light: light_type.second) {
      draw_point(light->get_pos());
    }
  }
}

void Renderer::render(std::vector<RenderObject>& render_list) {
  int draw_calls = 0;
  pre_render();
  draw_debug_info(render_list);
  render_depth_test(render_list);

  glDisable(GL_BLEND);
  glBlendFunc(GL_ONE, GL_ONE);
  //foreach type of light
  for(auto& light_type: lights) {
    if(light_type.second.size() == 0) {
      continue;
    }
    std::shared_ptr<LightShader> shader = light_type.first;
    //foreach light instance

    shader->use_shader();
    for(auto& light: light_type.second) {
      if(shown_light_index != -1 && light_list[shown_light_index] != light) {
        continue;
      }
      //Might need static_cast
      shader->set_light(*light);
      //foreach vertex format
      VertexArray& vertex_format = (*render_list[0].mesh.vertex_array);
      vertex_format.bind();
      for(auto& render_object: render_list) {
        if((*render_object.mesh.vertex_array) != vertex_format) {
          vertex_format.unbind();
          vertex_format = (*render_object.mesh.vertex_array);
          vertex_format.bind();
        }
        const glm::mat4& obj_model_mat = render_object.transform.get_model_matrix();

        glm::mat4 mvp_mat = glm::mat4();
        mvp_mat *= perspective_mat;
        mvp_mat *= camera->get_view_mat();
        mvp_mat *= obj_model_mat;
        shader->set_mvp_mat(mvp_mat);
        shader->set_model_mat(obj_model_mat);

        shader->set_eye_pos(camera->pos);
        shader->set_eye_dir(camera->dir);

        shader->set_diffuse_sampler(0);
        render_object.bind_diffuse();

        shader->set_normal_sampler(1);
        render_object.bind_normal();

        shader->set_specular_sampler(2);
        render_object.bind_specular();

        shader->set_mask_sampler(3);
        render_object.bind_mask();

        if(light->casts_shadow()) {
          glm::mat4 depth_mvp_mat = glm::mat4();
          depth_mvp_mat *= light->get_projection();
          depth_mvp_mat *= light->get_view_mat();
          depth_mvp_mat *= obj_model_mat;
          depth_mvp_mat = depth_bias_mat * depth_mvp_mat;
          shader->set_depth_mvp_mat(depth_mvp_mat);

          light->shadow_map.bind_shadowmap(GL_TEXTURE4);
          shader->set_shadow_sampler(4);
        }

        shader->set_material(render_object.mesh.material);
        draw_calls++;
        render_object.render();
      }
      glEnable(GL_BLEND);
    }
  }
  draw_sky();
  DebugText::set_value("draw calls", draw_calls);
}

void Renderer::draw_aabb(const AABB& aabb) {
  glEnable(GL_BLEND);
  glm::mat4 vp_mat = glm::mat4();
  vp_mat *= perspective_mat;
  vp_mat *= camera->get_view_mat();
  debug_renderer.draw_aabb(aabb, vp_mat);
}

void Renderer::draw_lines(const std::vector<std::pair<glm::vec3, glm::vec3>>& lines, const glm::vec3& color) {
  glEnable(GL_BLEND);
  glm::mat4 mvp_mat = glm::mat4();
  mvp_mat *= perspective_mat;
  mvp_mat *= camera->get_view_mat();
  debug_renderer.draw_lines(lines, mvp_mat, color);
}

void Renderer::draw_line(const glm::vec3& from, const glm::vec3& to, const glm::vec3& color) {
  glEnable(GL_BLEND);
  glm::mat4 mvp_mat = glm::mat4();
  mvp_mat *= perspective_mat;
  mvp_mat *= camera->get_view_mat();
  debug_renderer.draw_line(from, to, mvp_mat, color);
}

void Renderer::draw_point(const glm::vec3& pos) {
  glm::mat4 mvp_mat = glm::mat4();
  mvp_mat *= perspective_mat;
  mvp_mat *= camera->get_view_mat();
  debug_renderer.draw_point(pos, mvp_mat);
}

void Renderer::toggle_wireframe() {
  static int mode = 0;
  mode++;
  switch(mode) {
    default:
      glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
      mode = 0;
      break;
    case 1:
      glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
      break;
    case 2:
      glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
      break;
  }
}

void Renderer::add_light(std::shared_ptr<PointLight> point_light) {
  lights[point_light_shader].push_back(point_light);
  light_list.push_back(point_light);
  DebugText::set_value("Num lights", light_count());
}

void Renderer::add_light(std::shared_ptr<SpotLight> spot_light) {
  lights[spot_light_shader].push_back(spot_light);
  light_list.push_back(spot_light);
  DebugText::set_value("Num lights", light_count());
}

void Renderer::add_light(std::shared_ptr<DirLight> dir_light) {
  lights[dir_light_shader].push_back(dir_light);
  light_list.push_back(dir_light);
  DebugText::set_value("Num lights", light_count());
}

void Renderer::show_single_light(int index) {
  last_shown_light_index = fmax(0, shown_light_index);
  index = fmax(-1, fmin(index, light_list.size() - 1));
  std::cout << "Show light " << index << "\n";
  shown_light_index = index;
}

std::shared_ptr<Light> Renderer::get_shown_light() {
  if(shown_light_index == -1) {
    return light_list[last_shown_light_index];
  } else {
    return light_list[shown_light_index];
  }
}

int Renderer::light_count() {
  return light_list.size();
}

void Renderer::set_skybox(RenderObject&& skybox) {
  this->skybox = std::make_unique<RenderObject>(skybox);
}

void Renderer::draw_sky() {
  if(skybox) {
    glDepthFunc(GL_EQUAL);
    glDepthRange(1, 1);
    skybox->transform.set_position(camera->pos);
    sky_shader();
    glm::mat4 mvp_mat = glm::mat4();
    mvp_mat *= perspective_mat;
    mvp_mat *= camera->get_view_mat();
    sky_shader.set_mvp_mat(mvp_mat);
    sky_shader.set_model_mat(skybox->transform.get_model_matrix());
    skybox->mesh.vertex_array->bind();
    skybox->render();
    skybox->mesh.vertex_array->unbind();
    sky_shader.stop();
    glDepthRange(0, 1);
    glDepthFunc(GL_LEQUAL);
  }
}

void Renderer::toggle_shadow_map() {
  draw_shadow_map = !draw_shadow_map;
}

void Renderer::clear_lights() {
  lights.clear();
  light_list.clear();
  DebugText::set_value("Num lights", 0);
}

bool vertex_array_sort(const RenderObject& left, const RenderObject& right) {
  return (*left.mesh.vertex_array) == (*right.mesh.vertex_array);
}

void Renderer::render(World& world) {
  render(world.render_list);
}
<|endoftext|>


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

// Author: Robert Davis

#include "glycam_module.h"

#include "gmml/gmml.h"

using gmml::Structure;

using namespace v8;

namespace gems {
namespace {

Handle<Value> set_from_glycam_sequence(const Arguments& args) {
    HandleScope scope;
    Local<v8::Object> obj = args.This();
    Structure *structure = gmml::glycam_build(*String::Utf8Value(args[0]));
    obj->SetHiddenValue(String::New("pointer"), External::New(structure));
    return scope.Close(Undefined());
}

}  // namespace

void GlycamModule::init(Handle<ObjectTemplate> global) {
    global->Set(String::New("_setFromGlycamSequence"),
                FunctionTemplate::New(set_from_glycam_sequence));
}

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

// Author: Robert Davis

#include "glycam_module.h"

#include "gmml/gmml.h"

using gmml::Structure;

using namespace v8;

namespace gems {
namespace {

Handle<Value> set_from_glycam_sequence(const Arguments& args) {
    HandleScope scope;
    Local<v8::Object> obj = args.This();
    try {
        Structure *structure = gmml::glycam_build(*String::Utf8Value(args[0]));
        obj->SetHiddenValue(String::New("pointer"), External::New(structure));
    } catch(const std::exception& e) {
        return scope.Close(ThrowException(String::New("Error in sequence.")));
    }
    return scope.Close(Undefined());
}

}  // namespace

void GlycamModule::init(Handle<ObjectTemplate> global) {
    global->Set(String::New("_setFromGlycamSequence"),
                FunctionTemplate::New(set_from_glycam_sequence));
}

}  // namespace gems
<|endoftext|>


<commit_before>#include <iostream>
#include <list>
#include <algorithm>

#include <Magick++/Image.h>
#include <Magick++/STL.h>

static std::string getInitializer(const std::string module)
{
  if ((module == "BGR") || (module == "CMYK") || (module =="RGB") || (module =="YUV"))
    return "interlace";
  return "";
}

int main() {
  std::list<Magick::CoderInfo> coderList;
  coderInfoList(&coderList, Magick::CoderInfo::TrueMatch, Magick::CoderInfo::AnyMatch, Magick::CoderInfo::AnyMatch);

  std::list<std::string> allowedNames;
  allowedNames.push_back("BGR");
  allowedNames.push_back("BMP");
  allowedNames.push_back("CMYK");
  allowedNames.push_back("DDS");
  allowedNames.push_back("EPT");
  allowedNames.push_back("FAX");
  allowedNames.push_back("HTML");
  allowedNames.push_back("JP2");
  allowedNames.push_back("JPEG");
  allowedNames.push_back("PCD");
  allowedNames.push_back("PCD");
  allowedNames.push_back("PDF");
  allowedNames.push_back("PNG");
  allowedNames.push_back("PS");
  allowedNames.push_back("PS2");
  allowedNames.push_back("PS3");
  allowedNames.push_back("RGB");
  allowedNames.push_back("SVG");
  allowedNames.push_back("TIFF");
  allowedNames.push_back("TXT");
  allowedNames.push_back("YCBCR");

  std::list<std::string> excludeList;
  excludeList.push_back("GRADIENT");
  excludeList.push_back("LABEL");
  excludeList.push_back("NULL");
  excludeList.push_back("PATTERN");
  excludeList.push_back("PLASMA");
  excludeList.push_back("SCREENSHOT");
  excludeList.push_back("XC");

  for (std::list<Magick::CoderInfo>::iterator it = coderList.begin(); it != coderList.end(); it++)
  {
    std::string module=(*it).module();
    if (std::find(excludeList.begin(), excludeList.end(), module) != excludeList.end())
      continue;

    if ((*it).name() == module)
      std::cout << ((*it).isWritable() ? "+" : "-") << module << ":" << getInitializer(module) << std::endl;
    else if (std::find(allowedNames.begin(), allowedNames.end(), module) != allowedNames.end())
      std::cout << ((*it).isWritable() ? "+" : "-") << (*it).name() << ":" << getInitializer(module) << std::endl;
  }
}
<commit_msg>Also added txt to the exclusion list because we keep hitting timeouts.<commit_after>#include <iostream>
#include <list>
#include <algorithm>

#include <Magick++/Image.h>
#include <Magick++/STL.h>

static std::string getInitializer(const std::string module)
{
  if ((module == "BGR") || (module == "CMYK") || (module =="RGB") || (module =="YUV"))
    return "interlace";
  return "";
}

int main() {
  std::list<Magick::CoderInfo> coderList;
  coderInfoList(&coderList, Magick::CoderInfo::TrueMatch, Magick::CoderInfo::AnyMatch, Magick::CoderInfo::AnyMatch);

  std::list<std::string> allowedNames;
  allowedNames.push_back("BGR");
  allowedNames.push_back("BMP");
  allowedNames.push_back("CMYK");
  allowedNames.push_back("DDS");
  allowedNames.push_back("EPT");
  allowedNames.push_back("FAX");
  allowedNames.push_back("HTML");
  allowedNames.push_back("JP2");
  allowedNames.push_back("JPEG");
  allowedNames.push_back("PCD");
  allowedNames.push_back("PCD");
  allowedNames.push_back("PDF");
  allowedNames.push_back("PNG");
  allowedNames.push_back("PS");
  allowedNames.push_back("PS2");
  allowedNames.push_back("PS3");
  allowedNames.push_back("RGB");
  allowedNames.push_back("SVG");
  allowedNames.push_back("TIFF");
  allowedNames.push_back("TXT");
  allowedNames.push_back("YCBCR");

  std::list<std::string> excludeList;
  excludeList.push_back("GRADIENT");
  excludeList.push_back("LABEL");
  excludeList.push_back("NULL");
  excludeList.push_back("PATTERN");
  excludeList.push_back("PLASMA");
  excludeList.push_back("SCREENSHOT");
  excludeList.push_back("TXT");
  excludeList.push_back("XC");

  for (std::list<Magick::CoderInfo>::iterator it = coderList.begin(); it != coderList.end(); it++)
  {
    std::string module=(*it).module();
    if (std::find(excludeList.begin(), excludeList.end(), module) != excludeList.end())
      continue;

    if ((*it).name() == module)
      std::cout << ((*it).isWritable() ? "+" : "-") << module << ":" << getInitializer(module) << std::endl;
    else if (std::find(allowedNames.begin(), allowedNames.end(), module) != allowedNames.end())
      std::cout << ((*it).isWritable() ? "+" : "-") << (*it).name() << ":" << getInitializer(module) << std::endl;
  }
}
<|endoftext|>


<commit_before>/******************************************************************************
** Copyright (c) 2013-2015, Intel Corporation                                **
** All rights reserved.                                                      **
**                                                                           **
** Redistribution and use in source and binary forms, with or without        **
** modification, are permitted provided that the following conditions        **
** are met:                                                                  **
** 1. Redistributions of source code must retain the above copyright         **
**    notice, this list of conditions and the following disclaimer.          **
** 2. Redistributions in binary form must reproduce the above copyright      **
**    notice, this list of conditions and the following disclaimer in the    **
**    documentation and/or other materials provided with the distribution.   **
** 3. Neither the name of the copyright holder nor the names of its          **
**    contributors may be used to endorse or promote products derived        **
**    from this software without specific prior written permission.          **
**                                                                           **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR     **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,    **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED  **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR    **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              **
******************************************************************************/
/* Hans Pabst (Intel Corp.)
******************************************************************************/
#include <libxsmm.h>

#if defined(LIBXSMM_OFFLOAD)
# pragma offload_attribute(push,target(mic))
#endif

#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <vector>
#include <cmath>

#if defined(_OPENMP)
# include <omp.h>
#endif

#if defined(LIBXSMM_OFFLOAD)
# pragma offload_attribute(pop)
#endif

#if (0 < (LIBXSMM_ALIGNED_STORES))
# define SMM_ALIGNMENT LIBXSMM_ALIGNED_STORES
#else
# define SMM_ALIGNMENT LIBXSMM_ALIGNMENT
#endif

// make sure that stacksize is covering the problem size
#define SMM_MAX_PROBLEM_SIZE (5 * LIBXSMM_MAX_MNK)

#define SMM_SCHEDULE dynamic
#define SMM_CHECK

template<typename T>
LIBXSMM_TARGET(mic) void nrand(T& a)
{
  static const double scale = 1.0 / RAND_MAX;
  a = static_cast<T>(scale * (2 * std::rand() - RAND_MAX));
}

template<typename T>
LIBXSMM_TARGET(mic) void add(T *LIBXSMM_RESTRICT dst, const T *LIBXSMM_RESTRICT c, int m, int n, int ldc)
{
#if (0 < LIBXSMM_ALIGNED_STORES)
  LIBXSMM_ASSUME_ALIGNED(c, SMM_ALIGNMENT);
#endif
  for (int i = 0; i < m; ++i) {
    for (int j = 0; j < n; ++j) {
#if (0 != LIBXSMM_ROW_MAJOR)
      const T value = c[i*ldc+j];
#else
      const T value = c[j*ldc+i];
#endif
#if defined(_OPENMP)
#     pragma omp atomic
#endif
#if (0 != LIBXSMM_ROW_MAJOR)
      dst[i*n+j] += value;
#else
      dst[j*m+i] += value;
#endif
    }
  }
}

template<typename T>
LIBXSMM_TARGET(mic) double max_diff(const T *LIBXSMM_RESTRICT result, const T *LIBXSMM_RESTRICT expect, int m, int n, int ldc)
{
  double diff = 0;
  for (int i = 0; i < m; ++i) {
    for (int j = 0; j < n; ++j) {
#if (0 != LIBXSMM_ROW_MAJOR)
      const int k = i * ldc + j;
#else
      const int k = j * ldc + i;
#endif
      diff = std::max(diff, std::abs(static_cast<double>(result[k]) - static_cast<double>(expect[k])));
    }
  }
  return diff;
}

int main(int argc, char* argv[])
{
  try {
    typedef double T;
    const int default_psize = 500000, default_batch = 100;
    const int m = 1 < argc ? std::atoi(argv[1]) : 23;
    const int s = 2 < argc ? (0 < std::atoi(argv[2]) ? std::atoi(argv[2]) : ('+' == *argv[2]
      ? (default_psize << std::strlen(argv[2]))
      : (default_psize >> std::strlen(argv[2])))) : default_psize;
    const int t = 3 < argc ? (0 < std::atoi(argv[3]) ? std::atoi(argv[3]) : ('+' == *argv[3]
      ? (default_batch << std::strlen(argv[3]))
      : (default_batch >> std::strlen(argv[3])))) : default_batch;
    const int n = 4 < argc ? std::atoi(argv[4]) : m;
    const int k = 5 < argc ? std::atoi(argv[5]) : m;

#if (0 != LIBXSMM_ALIGNED_STORES)
# if (0 != LIBXSMM_ROW_MAJOR)
    const int ldc = LIBXSMM_ALIGN_VALUE(int, T, n, LIBXSMM_ALIGNED_STORES);
    const int csize = m * ldc + (LIBXSMM_ALIGNED_STORES) / sizeof(T) - 1;
# else
    const int ldc = LIBXSMM_ALIGN_VALUE(int, T, m, LIBXSMM_ALIGNED_STORES);
    const int csize = n * ldc + (LIBXSMM_ALIGNED_STORES) / sizeof(T) - 1;
# endif
#else
# if (0 != LIBXSMM_ROW_MAJOR)
    const int ldc = n, csize = m * ldc;
# else
    const int ldc = m, csize = n * ldc;
# endif
#endif

    const int asize = m * k, bsize = k * n;
    std::vector<T> va(s * asize), vb(s * bsize), vc(csize);
    std::for_each(va.begin(), va.end(), nrand<T>);
    std::for_each(vb.begin(), vb.end(), nrand<T>);
    const T *const a = &va[0], *const b = &vb[0];
    T */*const*/ c = &vc[0];

#if defined(LIBXSMM_OFFLOAD)
#   pragma offload target(mic) in(a: length(s * asize)) in(b: length(s * bsize)) out(c: length(csize))
#endif
    {
      const double mbytes = 1.0 * s * (asize + bsize) * sizeof(T) / (1024 * 1024);
      const double nbytes = 1.0 * s * (csize) * sizeof(T) / (1024 * 1024);
#if defined(_OPENMP)
      const double gflops = 2.0 * s * m * n * k * 1E-9;
#endif
#if defined(SMM_CHECK)
      std::vector<T> expect(csize);
#endif
      fprintf(stdout, "m=%i n=%i k=%i ldc=%i size=%i batch=%i memory=%.1f MB\n", m, n, k, ldc, s, t, mbytes);

      { // LAPACK/BLAS3 (fallback)
        fprintf(stdout, "LAPACK/BLAS...\n");
        std::fill_n(c, csize, 0);
#if defined(_OPENMP)
        const double start = omp_get_wtime();
#       pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
        for (int i = 0; i < s; i += t) {
          LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
          for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
          for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
            libxsmm_blasmm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
          }
          add(c, tmp, m, n, ldc); // atomic
        }
#if defined(_OPENMP)
        const double duration = omp_get_wtime() - start;
        if (0 < duration) {
          fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
          fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
        }
        fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
        std::copy(c, c + csize, expect.begin());
#endif
      }

      { // inline an optimized implementation
        fprintf(stdout, "Inlined...\n");
        std::fill_n(c, csize, 0);
#if defined(_OPENMP)
        const double start = omp_get_wtime();
#       pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
        for (int i = 0; i < s; i += t) {
          LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
          for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
          for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
            libxsmm_imm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
          }
          add(c, tmp, m, n, ldc); // atomic
        }
#if defined(_OPENMP)
        const double duration = omp_get_wtime() - start;
        if (0 < duration) {
          fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
          fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
        }
        fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
        fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc));
#endif
      }

      { // auto-dispatched
        fprintf(stdout, "Dispatched...\n");
        std::fill_n(c, csize, 0);
#if defined(_OPENMP)
        const double start = omp_get_wtime();
#       pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
        for (int i = 0; i < s; i += t) {
          LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
          for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
          for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
            libxsmm_mm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
          }
          add(c, tmp, m, n, ldc); // atomic
        }
#if defined(_OPENMP)
        const double duration = omp_get_wtime() - start;
        if (0 < duration) {
          fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
          fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
        }
        fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
        fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc));
#endif
      }

      const libxsmm_mm_dispatch<T> xmm(m, n, k);
      if (xmm) { // specialized routine
        fprintf(stdout, "Specialized...\n");
        std::fill_n(c, csize, 0);
#if defined(_OPENMP)
        const double start = omp_get_wtime();
#       pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
        for (int i = 0; i < s; i += t) {
          LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
          for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
          for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
            xmm(&a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
          }
          add(c, tmp, m, n, ldc); // atomic
        }
#if defined(_OPENMP)
        const double duration = omp_get_wtime() - start;
        if (0 < duration) {
          fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
          fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
        }
        fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
        fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc));
#endif
      }

      fprintf(stdout, "Finished\n");
    }
  }
  catch(const std::exception& e) {
    fprintf(stderr, "Error: %s\n", e.what());
    return EXIT_FAILURE;
  }
  catch(...) {
    fprintf(stderr, "Error: unknown exception caught!\n");
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}
<commit_msg>Rely on a smaller matrix stack (similar to CP2K's default stack metric).<commit_after>/******************************************************************************
** Copyright (c) 2013-2015, Intel Corporation                                **
** All rights reserved.                                                      **
**                                                                           **
** Redistribution and use in source and binary forms, with or without        **
** modification, are permitted provided that the following conditions        **
** are met:                                                                  **
** 1. Redistributions of source code must retain the above copyright         **
**    notice, this list of conditions and the following disclaimer.          **
** 2. Redistributions in binary form must reproduce the above copyright      **
**    notice, this list of conditions and the following disclaimer in the    **
**    documentation and/or other materials provided with the distribution.   **
** 3. Neither the name of the copyright holder nor the names of its          **
**    contributors may be used to endorse or promote products derived        **
**    from this software without specific prior written permission.          **
**                                                                           **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR     **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,    **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED  **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR    **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              **
******************************************************************************/
/* Hans Pabst (Intel Corp.)
******************************************************************************/
#include <libxsmm.h>

#if defined(LIBXSMM_OFFLOAD)
# pragma offload_attribute(push,target(mic))
#endif

#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <vector>
#include <cmath>

#if defined(_OPENMP)
# include <omp.h>
#endif

#if defined(LIBXSMM_OFFLOAD)
# pragma offload_attribute(pop)
#endif

#if (0 < (LIBXSMM_ALIGNED_STORES))
# define SMM_ALIGNMENT LIBXSMM_ALIGNED_STORES
#else
# define SMM_ALIGNMENT LIBXSMM_ALIGNMENT
#endif

// make sure that stacksize is covering the problem size
#define SMM_MAX_PROBLEM_SIZE (5 * LIBXSMM_MAX_MNK)

#define SMM_SCHEDULE dynamic
#define SMM_CHECK

template<typename T>
LIBXSMM_TARGET(mic) void nrand(T& a)
{
  static const double scale = 1.0 / RAND_MAX;
  a = static_cast<T>(scale * (2 * std::rand() - RAND_MAX));
}

template<typename T>
LIBXSMM_TARGET(mic) void add(T *LIBXSMM_RESTRICT dst, const T *LIBXSMM_RESTRICT c, int m, int n, int ldc)
{
#if (0 < LIBXSMM_ALIGNED_STORES)
  LIBXSMM_ASSUME_ALIGNED(c, SMM_ALIGNMENT);
#endif
  for (int i = 0; i < m; ++i) {
    for (int j = 0; j < n; ++j) {
#if (0 != LIBXSMM_ROW_MAJOR)
      const T value = c[i*ldc+j];
#else
      const T value = c[j*ldc+i];
#endif
#if defined(_OPENMP)
#     pragma omp atomic
#endif
#if (0 != LIBXSMM_ROW_MAJOR)
      dst[i*n+j] += value;
#else
      dst[j*m+i] += value;
#endif
    }
  }
}

template<typename T>
LIBXSMM_TARGET(mic) double max_diff(const T *LIBXSMM_RESTRICT result, const T *LIBXSMM_RESTRICT expect, int m, int n, int ldc)
{
  double diff = 0;
  for (int i = 0; i < m; ++i) {
    for (int j = 0; j < n; ++j) {
#if (0 != LIBXSMM_ROW_MAJOR)
      const int k = i * ldc + j;
#else
      const int k = j * ldc + i;
#endif
      diff = std::max(diff, std::abs(static_cast<double>(result[k]) - static_cast<double>(expect[k])));
    }
  }
  return diff;
}

int main(int argc, char* argv[])
{
  try {
    typedef double T;
    const int default_psize = 30000, default_batch = 1000;
    const int m = 1 < argc ? std::atoi(argv[1]) : 23;
    const int s = 2 < argc ? (0 < std::atoi(argv[2]) ? std::atoi(argv[2]) : ('+' == *argv[2]
      ? (default_psize << std::strlen(argv[2]))
      : (default_psize >> std::strlen(argv[2])))) : default_psize;
    const int t = 3 < argc ? (0 < std::atoi(argv[3]) ? std::atoi(argv[3]) : ('+' == *argv[3]
      ? (default_batch << std::strlen(argv[3]))
      : (default_batch >> std::strlen(argv[3])))) : default_batch;
    const int n = 4 < argc ? std::atoi(argv[4]) : m;
    const int k = 5 < argc ? std::atoi(argv[5]) : m;

#if (0 != LIBXSMM_ALIGNED_STORES)
# if (0 != LIBXSMM_ROW_MAJOR)
    const int ldc = LIBXSMM_ALIGN_VALUE(int, T, n, LIBXSMM_ALIGNED_STORES);
    const int csize = m * ldc + (LIBXSMM_ALIGNED_STORES) / sizeof(T) - 1;
# else
    const int ldc = LIBXSMM_ALIGN_VALUE(int, T, m, LIBXSMM_ALIGNED_STORES);
    const int csize = n * ldc + (LIBXSMM_ALIGNED_STORES) / sizeof(T) - 1;
# endif
#else
# if (0 != LIBXSMM_ROW_MAJOR)
    const int ldc = n, csize = m * ldc;
# else
    const int ldc = m, csize = n * ldc;
# endif
#endif

    const int asize = m * k, bsize = k * n;
    std::vector<T> va(s * asize), vb(s * bsize), vc(csize);
    std::for_each(va.begin(), va.end(), nrand<T>);
    std::for_each(vb.begin(), vb.end(), nrand<T>);
    const T *const a = &va[0], *const b = &vb[0];
    T */*const*/ c = &vc[0];

#if defined(LIBXSMM_OFFLOAD)
#   pragma offload target(mic) in(a: length(s * asize)) in(b: length(s * bsize)) out(c: length(csize))
#endif
    {
      const double mbytes = 1.0 * s * (asize + bsize) * sizeof(T) / (1024 * 1024);
      const double nbytes = 1.0 * s * (csize) * sizeof(T) / (1024 * 1024);
#if defined(_OPENMP)
      const double gflops = 2.0 * s * m * n * k * 1E-9;
#endif
#if defined(SMM_CHECK)
      std::vector<T> expect(csize);
#endif
      fprintf(stdout, "m=%i n=%i k=%i ldc=%i size=%i batch=%i memory=%.1f MB\n", m, n, k, ldc, s, t, mbytes);

      { // LAPACK/BLAS3 (fallback)
        fprintf(stdout, "LAPACK/BLAS...\n");
        std::fill_n(c, csize, 0);
#if defined(_OPENMP)
        const double start = omp_get_wtime();
#       pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
        for (int i = 0; i < s; i += t) {
          LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
          for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
          for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
            libxsmm_blasmm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
          }
          add(c, tmp, m, n, ldc); // atomic
        }
#if defined(_OPENMP)
        const double duration = omp_get_wtime() - start;
        if (0 < duration) {
          fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
          fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
        }
        fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
        std::copy(c, c + csize, expect.begin());
#endif
      }

      { // inline an optimized implementation
        fprintf(stdout, "Inlined...\n");
        std::fill_n(c, csize, 0);
#if defined(_OPENMP)
        const double start = omp_get_wtime();
#       pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
        for (int i = 0; i < s; i += t) {
          LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
          for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
          for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
            libxsmm_imm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
          }
          add(c, tmp, m, n, ldc); // atomic
        }
#if defined(_OPENMP)
        const double duration = omp_get_wtime() - start;
        if (0 < duration) {
          fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
          fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
        }
        fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
        fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc));
#endif
      }

      { // auto-dispatched
        fprintf(stdout, "Dispatched...\n");
        std::fill_n(c, csize, 0);
#if defined(_OPENMP)
        const double start = omp_get_wtime();
#       pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
        for (int i = 0; i < s; i += t) {
          LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
          for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
          for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
            libxsmm_mm(m, n, k, &a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
          }
          add(c, tmp, m, n, ldc); // atomic
        }
#if defined(_OPENMP)
        const double duration = omp_get_wtime() - start;
        if (0 < duration) {
          fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
          fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
        }
        fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
        fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc));
#endif
      }

      const libxsmm_mm_dispatch<T> xmm(m, n, k);
      if (xmm) { // specialized routine
        fprintf(stdout, "Specialized...\n");
        std::fill_n(c, csize, 0);
#if defined(_OPENMP)
        const double start = omp_get_wtime();
#       pragma omp parallel for schedule(SMM_SCHEDULE)
#endif
        for (int i = 0; i < s; i += t) {
          LIBXSMM_ALIGNED(T tmp[SMM_MAX_PROBLEM_SIZE], SMM_ALIGNMENT);
          for (int j = 0; j < csize; ++j) tmp[j] = 0; // clear
          for (int j = 0; j < LIBXSMM_MIN(t, s - i); ++j) {
            xmm(&a[0] + (i + j) * asize, &b[0] + (i + j) * bsize, tmp);
          }
          add(c, tmp, m, n, ldc); // atomic
        }
#if defined(_OPENMP)
        const double duration = omp_get_wtime() - start;
        if (0 < duration) {
          fprintf(stdout, "\tperformance: %.1f GFLOPS/s\n", gflops / duration);
          fprintf(stdout, "\tbandwidth: %.1f GB/s\n", (mbytes + nbytes) * 1E-3 / duration);
        }
        fprintf(stdout, "\tduration: %.1f s\n", duration);
#endif
#if defined(SMM_CHECK)
        fprintf(stdout, "\tdiff=%f\n", max_diff(c, &expect[0], m, n, ldc));
#endif
      }

      fprintf(stdout, "Finished\n");
    }
  }
  catch(const std::exception& e) {
    fprintf(stderr, "Error: %s\n", e.what());
    return EXIT_FAILURE;
  }
  catch(...) {
    fprintf(stderr, "Error: unknown exception caught!\n");
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
#include <berryWorkbenchPlugin.h>
#include <berryIQtStyleManager.h>

// Qmitk
#include "ChartExample.h"

// Qt
#include <QMessageBox>
#include <QRandomGenerator>

// mitk image
#include <mitkImage.h>

const std::string ChartExample::VIEW_ID = "org.mitk.views.chartexample";

void ChartExample::SetFocus()
{
  m_Controls.m_buttonCreateChart->setFocus();
}

void ChartExample::CreateQtPartControl(QWidget *parent)
{
  // create GUI widgets from the Qt Designer's .ui file
  m_Controls.setupUi(parent);
  connect(m_Controls.m_buttonCreateChart, &QPushButton::clicked, this, &ChartExample::CreateChart);
  connect(m_Controls.m_buttonClearChart, &QPushButton::clicked, this, &ChartExample::ClearChart);
  connect(m_Controls.m_buttonAddData, &QPushButton::clicked, this, &ChartExample::AddData);

  FillRandomDataValues();

  m_Controls.m_Chart->SetTheme(GetColorTheme());

  m_Controls.m_lineEditXAxisLabel->setText("xLabel");
  m_Controls.m_lineEditYAxisLabel->setText("yLabel");

  m_chartNameToChartType.emplace("bar", QmitkChartWidget::ChartType::bar);
  m_chartNameToChartType.emplace("line", QmitkChartWidget::ChartType::line);
  m_chartNameToChartType.emplace("spline", QmitkChartWidget::ChartType::spline);
  m_chartNameToChartType.emplace("pie", QmitkChartWidget::ChartType::pie);
  m_chartNameToChartType.emplace("area", QmitkChartWidget::ChartType::area);
  m_chartNameToChartType.emplace("area-spline", QmitkChartWidget::ChartType::area_spline);
  m_chartNameToChartType.emplace("scatter", QmitkChartWidget::ChartType::scatter);

  m_LineNameToLineType.emplace("solid", QmitkChartWidget::LineStyle::solid);
  m_LineNameToLineType.emplace("dashed", QmitkChartWidget::LineStyle::dashed);

  m_AxisScaleNameToAxisScaleType.emplace("linear", QmitkChartWidget::AxisScale::linear);
  m_AxisScaleNameToAxisScaleType.emplace("log", QmitkChartWidget::AxisScale::log);
}

void ChartExample::FillRandomDataValues()
{
  std::vector<double> numbers = generateRandomNumbers(10, 10.0);
  std::string text = convertToText(numbers, ";");
  m_Controls.m_lineEditDataVector->setText(QString::fromStdString(text));

  m_Controls.m_lineEditDataLabel->setText("test" + QString::number(countForUID));
  countForUID++;
}

void ChartExample::CreateChart()
{
  auto dataYAxisScaleType = m_AxisScaleNameToAxisScaleType.at(m_Controls.m_comboBoxYAxisScale->currentText().toStdString());
  auto xAxisLabel = m_Controls.m_lineEditXAxisLabel->text().toStdString();
  auto yAxisLabel = m_Controls.m_lineEditYAxisLabel->text().toStdString();
  auto showLegend = m_Controls.m_checkBoxShowLegend->isChecked();
  auto showDataPoints = m_Controls.m_checkBoxShowDataPoints->isChecked();
  auto stackedData = m_Controls.m_checkBoxStackedData->isChecked();
  auto showSubchart = m_Controls.m_checkBoxShowSubchart->isChecked();

  m_Controls.m_Chart->SetYAxisScale(dataYAxisScaleType);
  m_Controls.m_Chart->SetXAxisLabel(xAxisLabel);
  m_Controls.m_Chart->SetYAxisLabel(yAxisLabel);
  m_Controls.m_Chart->SetShowLegend(showLegend);
  m_Controls.m_Chart->SetShowDataPoints(showDataPoints);
  m_Controls.m_Chart->SetStackedData(stackedData);
  m_Controls.m_Chart->Show(showSubchart);
}

void ChartExample::ClearChart()
{
  m_Controls.m_Chart->Clear();
  m_Controls.m_plainTextEditDataView->clear();
}

void ChartExample::AddData()
{
  auto lineEditData = m_Controls.m_lineEditDataVector->text();
  std::vector<double> data;
  for(const QString entry : lineEditData.split(';'))
  {
    data.push_back(entry.toDouble());
  }

  auto chartType = m_chartNameToChartType.at(m_Controls.m_comboBoxChartType->currentText().toStdString());
  std::string dataLabel = m_Controls.m_lineEditDataLabel->text().toStdString();
  std::string dataColor = m_Controls.m_lineEditColor->text().toStdString();
  auto dataLineStyleType = m_LineNameToLineType.at(m_Controls.m_comboBoxLineStyle->currentText().toStdString());

  m_Controls.m_Chart->AddData1D(data, dataLabel, chartType);
  if (!dataColor.empty()) {
    m_Controls.m_Chart->SetColor(dataLabel, dataColor);
  }
  m_Controls.m_Chart->SetLineStyle(dataLabel, dataLineStyleType);

  QString dataOverview;
  dataOverview.append(m_Controls.m_lineEditDataLabel->text());
  dataOverview.append("(").append(m_Controls.m_comboBoxChartType->currentText());
  if (!dataColor.empty()) {
    dataOverview.append(", ").append(dataColor.c_str());
  }
  dataOverview.append(", ").append(m_Controls.m_comboBoxLineStyle->currentText());
  dataOverview.append(")");
  dataOverview.append(":").append(lineEditData);

  m_Controls.m_plainTextEditDataView->appendPlainText(dataOverview);

  FillRandomDataValues();
}

std::vector<double> ChartExample::generateRandomNumbers(unsigned int amount, double max) const
{
  QRandomGenerator gen;
  gen.seed(time(NULL));

  std::vector<double> data;
  for (unsigned int i = 0; i < amount; i++) {
    data.push_back(gen.bounded(max));
  }

  return data;
}

std::string ChartExample::convertToText(std::vector<double> numbers, std::string delimiter) const
{
  std::ostringstream oss;
  oss.precision(3);

  if (!numbers.empty())
  {
    for (auto number : numbers) {
      oss << number << delimiter;
    }
  }
  auto aString = oss.str();
  aString.pop_back();
  return aString;
}

QmitkChartWidget::ChartStyle ChartExample::GetColorTheme() const
{
  ctkPluginContext* context = berry::WorkbenchPlugin::GetDefault()->GetPluginContext();
  ctkServiceReference styleManagerRef = context->getServiceReference<berry::IQtStyleManager>();
  if (styleManagerRef)
  {
    auto styleManager = context->getService<berry::IQtStyleManager>(styleManagerRef);
    if (styleManager->GetStyle().name == "Dark") {
      return QmitkChartWidget::ChartStyle::darkstyle;
    }
    else {
      return QmitkChartWidget::ChartStyle::lightstyle;
    }
  }
  return QmitkChartWidget::ChartStyle::darkstyle;
}

<commit_msg>fixed a bug to show logarithmic axis scale<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
#include <berryWorkbenchPlugin.h>
#include <berryIQtStyleManager.h>

// Qmitk
#include "ChartExample.h"

// Qt
#include <QMessageBox>
#include <QRandomGenerator>

// mitk image
#include <mitkImage.h>

const std::string ChartExample::VIEW_ID = "org.mitk.views.chartexample";

void ChartExample::SetFocus()
{
  m_Controls.m_buttonCreateChart->setFocus();
}

void ChartExample::CreateQtPartControl(QWidget *parent)
{
  // create GUI widgets from the Qt Designer's .ui file
  m_Controls.setupUi(parent);
  connect(m_Controls.m_buttonCreateChart, &QPushButton::clicked, this, &ChartExample::CreateChart);
  connect(m_Controls.m_buttonClearChart, &QPushButton::clicked, this, &ChartExample::ClearChart);
  connect(m_Controls.m_buttonAddData, &QPushButton::clicked, this, &ChartExample::AddData);

  FillRandomDataValues();

  m_Controls.m_Chart->SetTheme(GetColorTheme());

  m_Controls.m_lineEditXAxisLabel->setText("xLabel");
  m_Controls.m_lineEditYAxisLabel->setText("yLabel");

  m_chartNameToChartType.emplace("bar", QmitkChartWidget::ChartType::bar);
  m_chartNameToChartType.emplace("line", QmitkChartWidget::ChartType::line);
  m_chartNameToChartType.emplace("spline", QmitkChartWidget::ChartType::spline);
  m_chartNameToChartType.emplace("pie", QmitkChartWidget::ChartType::pie);
  m_chartNameToChartType.emplace("area", QmitkChartWidget::ChartType::area);
  m_chartNameToChartType.emplace("area-spline", QmitkChartWidget::ChartType::area_spline);
  m_chartNameToChartType.emplace("scatter", QmitkChartWidget::ChartType::scatter);

  m_LineNameToLineType.emplace("solid", QmitkChartWidget::LineStyle::solid);
  m_LineNameToLineType.emplace("dashed", QmitkChartWidget::LineStyle::dashed);

  m_AxisScaleNameToAxisScaleType.emplace("linear", QmitkChartWidget::AxisScale::linear);
  m_AxisScaleNameToAxisScaleType.emplace("logarithmic", QmitkChartWidget::AxisScale::log);
}

void ChartExample::FillRandomDataValues()
{
  std::vector<double> numbers = generateRandomNumbers(10, 10.0);
  std::string text = convertToText(numbers, ";");
  m_Controls.m_lineEditDataVector->setText(QString::fromStdString(text));

  m_Controls.m_lineEditDataLabel->setText("test" + QString::number(countForUID));
  countForUID++;
}

void ChartExample::CreateChart()
{
  auto dataYAxisScaleType = m_AxisScaleNameToAxisScaleType.at(m_Controls.m_comboBoxYAxisScale->currentText().toStdString());
  auto xAxisLabel = m_Controls.m_lineEditXAxisLabel->text().toStdString();
  auto yAxisLabel = m_Controls.m_lineEditYAxisLabel->text().toStdString();
  auto showLegend = m_Controls.m_checkBoxShowLegend->isChecked();
  auto showDataPoints = m_Controls.m_checkBoxShowDataPoints->isChecked();
  auto stackedData = m_Controls.m_checkBoxStackedData->isChecked();
  auto showSubchart = m_Controls.m_checkBoxShowSubchart->isChecked();

  m_Controls.m_Chart->SetYAxisScale(dataYAxisScaleType);
  m_Controls.m_Chart->SetXAxisLabel(xAxisLabel);
  m_Controls.m_Chart->SetYAxisLabel(yAxisLabel);
  m_Controls.m_Chart->SetShowLegend(showLegend);
  m_Controls.m_Chart->SetShowDataPoints(showDataPoints);
  m_Controls.m_Chart->SetStackedData(stackedData);
  m_Controls.m_Chart->Show(showSubchart);
}

void ChartExample::ClearChart()
{
  m_Controls.m_Chart->Clear();
  m_Controls.m_plainTextEditDataView->clear();
}

void ChartExample::AddData()
{
  auto lineEditData = m_Controls.m_lineEditDataVector->text();
  std::vector<double> data;
  for(const QString entry : lineEditData.split(';'))
  {
    data.push_back(entry.toDouble());
  }

  auto chartType = m_chartNameToChartType.at(m_Controls.m_comboBoxChartType->currentText().toStdString());
  std::string dataLabel = m_Controls.m_lineEditDataLabel->text().toStdString();
  std::string dataColor = m_Controls.m_lineEditColor->text().toStdString();
  auto dataLineStyleType = m_LineNameToLineType.at(m_Controls.m_comboBoxLineStyle->currentText().toStdString());

  m_Controls.m_Chart->AddData1D(data, dataLabel, chartType);
  if (!dataColor.empty()) {
    m_Controls.m_Chart->SetColor(dataLabel, dataColor);
  }
  m_Controls.m_Chart->SetLineStyle(dataLabel, dataLineStyleType);

  QString dataOverview;
  dataOverview.append(m_Controls.m_lineEditDataLabel->text());
  dataOverview.append("(").append(m_Controls.m_comboBoxChartType->currentText());
  if (!dataColor.empty()) {
    dataOverview.append(", ").append(dataColor.c_str());
  }
  dataOverview.append(", ").append(m_Controls.m_comboBoxLineStyle->currentText());
  dataOverview.append(")");
  dataOverview.append(":").append(lineEditData);

  m_Controls.m_plainTextEditDataView->appendPlainText(dataOverview);

  FillRandomDataValues();
}

std::vector<double> ChartExample::generateRandomNumbers(unsigned int amount, double max) const
{
  QRandomGenerator gen;
  gen.seed(time(NULL));

  std::vector<double> data;
  for (unsigned int i = 0; i < amount; i++) {
    data.push_back(gen.bounded(max));
  }

  return data;
}

std::string ChartExample::convertToText(std::vector<double> numbers, std::string delimiter) const
{
  std::ostringstream oss;
  oss.precision(3);

  if (!numbers.empty())
  {
    for (auto number : numbers) {
      oss << number << delimiter;
    }
  }
  auto aString = oss.str();
  aString.pop_back();
  return aString;
}

QmitkChartWidget::ChartStyle ChartExample::GetColorTheme() const
{
  ctkPluginContext* context = berry::WorkbenchPlugin::GetDefault()->GetPluginContext();
  ctkServiceReference styleManagerRef = context->getServiceReference<berry::IQtStyleManager>();
  if (styleManagerRef)
  {
    auto styleManager = context->getService<berry::IQtStyleManager>(styleManagerRef);
    if (styleManager->GetStyle().name == "Dark") {
      return QmitkChartWidget::ChartStyle::darkstyle;
    }
    else {
      return QmitkChartWidget::ChartStyle::lightstyle;
    }
  }
  return QmitkChartWidget::ChartStyle::darkstyle;
}

<|endoftext|>


<commit_before>
#ifndef CALIB_HPP_Q5H9DDXY
#define CALIB_HPP_Q5H9DDXY

#include <image.hpp>
#include <improc.hpp>
#include <region.hpp>
#include <linalg.hpp>
#include <matfunc.hpp>

/*!
 * @brief Calculate object points for chessboard pattern used as calibration object.
 *
 * @param rows rows of corners present in the chessboard pattern.
 * @param cols columns of corners present in the chessboard pattern.
 * @param square_size real world size of the single chessboard square in generic units.
 *
 * @return
 * std::vector<cv::vec3r> world points of chessboard pattern with Z = 1, where X, Y is 2D homogenious point.
 */
std::vector<cv::vec3r> calculate_object_points(unsigned rows, unsigned cols, real_t square_size);

/*!
 * @brief Normalize image points used in calibration process.
 *
 * @param patterns vector of vector<cv::vec2r>, as in list of chessboard pattern image point corners.
 * @param w width of the image from which the pattern is extracted.
 * @param h height of the image from which the pattern is extracted.
 *
 * @return
 * Returns normalization matrix:
 * [2/w		0		-1]
 * [0		2/h		-1
 * [0		0		1]
 */
cv::matrixr normalize_image_points(std::vector<std::vector<cv::vec2r> > &patterns, unsigned w, unsigned h);

/*!
 * @brief Denormalize intrinsic matrix.
 *
 * @param A_p intrincis matrix calculated using normalized image points.
 * @param N Normalization matrix composed using normalize_image_points function.
 *
 * @return
 * De-normalized intrinsic matrix.
 */
cv::matrixr denormalize_intrinsics(const cv::matrixr &A_p, const cv::matrixr &N);

/*!
 * @brief Calculate reprojection for given world (model) point.
 *
 * @param world_ptn 4D model point.
 * @param A intrinsic matrix. (3x3)
 * @param K extrinsic matrix [R | t] (3x4)
 * @param k distortion cofficients.
 */
cv::vectorr reproject_point(const cv::vectorr &world_ptn, const cv::matrixr &A, const cv::matrixr &K, const cv::vec2r &k = cv::vec2r{0, 0});
/*!
 * @brief Calculate reprojection error using given intrinsic and extrinsic matrices, and image and world points
 * used to calculate those.
 *
 * @param A intrinsic 3x3 matrix
 * @param K extrinsic [r1 r2 r3 t] 3x4 matrix.
 * @param model_pts world points of the pattern used for calibration.
 * @param image_pts image points of the pattern used for calibration.
 * @param image_pts_proj vector of points where reprojected points will be stored.
 * @param camera_pts camera projection points - K * model
 *
 * @return
 * square error of reprojection.
 */
real_t calc_reprojection(const cv::matrixr &A, const cv::matrixr &K,
                               const std::vector<cv::vec3r> &model_pts, const std::vector<cv::vec2r> &image_pts, const std::vector<cv::vec2r> &image_pts_nrm,
                               std::vector<cv::vec2r> &image_pts_proj, std::vector<cv::vec3r> &camera_pts, cv::vec2r k = cv::vec2r());

/*!
 * @brief Compute intrinsic 3x3 matrix A from set of homography matrices calculated using calibration patterns.
 *
 * @param Hs vector of 3x3 homography matrices.
 *
 * @return
 * 3x3 intrinsic matrix A.
 */
cv::matrixr compute_intrisics(const std::vector<cv::matrixr> &Hs);

/*!
 * @brief Compute extrinsic 3x4 matrix using intrisic matrix and homogaphy matrix.
 *
 * @param A intrinsic 3x3 matrix.
 * @param H homography which relates one of pattern image corner points to world points of the pattern.
 *
 * @return
 * 3x4 extrinsic matrix.
 */
cv::matrixr compute_extrinsics(const cv::matrixr &A, const cv::matrixr &H);

/*!
 * @brief Compute lens distortion parameters k1, and k2.
 *
 * @param image_pts vector of calibration pattern corners.
 * @param image_pts_nrm normalized copy of image_pts, used originally for calibration.
 * @param image_pts_proj reprojected image points, calculated using calc_reprojection function.
 * @param A intrinsic matrix of the camera.
 *
 * @return
 * 2d real vector with [k1, k2] as values.
 */
cv::vec2r compute_distortion(const std::vector<std::vector<cv::vec2r>> &image_pts, const std::vector<std::vector<cv::vec2r>> &image_pts_nrm,
                             const std::vector<std::vector<cv::vec2r>> &image_pts_proj, const cv::matrixr &A);

/*!
 * @brief Draw the reprojected points, from world to image plane, using calculated camera parameters.
 *
 * Draws image points with smaller blue circle, and reprojection with larger red circles.
 *
 * @param image_pts image points from calibration pattern
 * @param image_pts_proj reprojected points calculated using calc_reprojection function
 * @param im_w image width
 * @param im_h image height
 */
cv::matrix3b draw_reprojection(const std::vector<cv::vec2r> &image_pts,
		const std::vector<cv::vec2r > &image_pts_proj, unsigned im_w, unsigned im_h);

#endif /* end of include guard: CALIB_HPP_Q5H9DDXY */

<commit_msg>added scale for drawing reprojection<commit_after>
#ifndef CALIB_HPP_Q5H9DDXY
#define CALIB_HPP_Q5H9DDXY

#include <image.hpp>
#include <improc.hpp>
#include <region.hpp>
#include <linalg.hpp>
#include <matfunc.hpp>

/*!
 * @brief Calculate object points for chessboard pattern used as calibration object.
 *
 * @param rows rows of corners present in the chessboard pattern.
 * @param cols columns of corners present in the chessboard pattern.
 * @param square_size real world size of the single chessboard square in generic units.
 *
 * @return
 * std::vector<cv::vec3r> world points of chessboard pattern with Z = 1, where X, Y is 2D homogenious point.
 */
std::vector<cv::vec3r> calculate_object_points(unsigned rows, unsigned cols, real_t square_size);

/*!
 * @brief Normalize image points used in calibration process.
 *
 * @param patterns vector of vector<cv::vec2r>, as in list of chessboard pattern image point corners.
 * @param w width of the image from which the pattern is extracted.
 * @param h height of the image from which the pattern is extracted.
 *
 * @return
 * Returns normalization matrix:
 * [2/w		0		-1]
 * [0		2/h		-1
 * [0		0		1]
 */
cv::matrixr normalize_image_points(std::vector<std::vector<cv::vec2r> > &patterns, unsigned w, unsigned h);

/*!
 * @brief Denormalize intrinsic matrix.
 *
 * @param A_p intrincis matrix calculated using normalized image points.
 * @param N Normalization matrix composed using normalize_image_points function.
 *
 * @return
 * De-normalized intrinsic matrix.
 */
cv::matrixr denormalize_intrinsics(const cv::matrixr &A_p, const cv::matrixr &N);

/*!
 * @brief Calculate reprojection for given world (model) point.
 *
 * @param world_ptn 4D model point.
 * @param A intrinsic matrix. (3x3)
 * @param K extrinsic matrix [R | t] (3x4)
 * @param k distortion cofficients.
 */
cv::vectorr reproject_point(const cv::vectorr &world_ptn, const cv::matrixr &A, const cv::matrixr &K, const cv::vec2r &k = cv::vec2r{0, 0});
/*!
 * @brief Calculate reprojection error using given intrinsic and extrinsic matrices, and image and world points
 * used to calculate those.
 *
 * @param A intrinsic 3x3 matrix
 * @param K extrinsic [r1 r2 r3 t] 3x4 matrix.
 * @param model_pts world points of the pattern used for calibration.
 * @param image_pts image points of the pattern used for calibration.
 * @param image_pts_proj vector of points where reprojected points will be stored.
 * @param camera_pts camera projection points - K * model
 *
 * @return
 * square error of reprojection.
 */
real_t calc_reprojection(const cv::matrixr &A, const cv::matrixr &K,
                               const std::vector<cv::vec3r> &model_pts, const std::vector<cv::vec2r> &image_pts, const std::vector<cv::vec2r> &image_pts_nrm,
                               std::vector<cv::vec2r> &image_pts_proj, std::vector<cv::vec3r> &camera_pts, cv::vec2r k = cv::vec2r());

/*!
 * @brief Compute intrinsic 3x3 matrix A from set of homography matrices calculated using calibration patterns.
 *
 * @param Hs vector of 3x3 homography matrices.
 *
 * @return
 * 3x3 intrinsic matrix A.
 */
cv::matrixr compute_intrisics(const std::vector<cv::matrixr> &Hs);

/*!
 * @brief Compute extrinsic 3x4 matrix using intrisic matrix and homogaphy matrix.
 *
 * @param A intrinsic 3x3 matrix.
 * @param H homography which relates one of pattern image corner points to world points of the pattern.
 *
 * @return
 * 3x4 extrinsic matrix.
 */
cv::matrixr compute_extrinsics(const cv::matrixr &A, const cv::matrixr &H);

/*!
 * @brief Compute lens distortion parameters k1, and k2.
 *
 * @param image_pts vector of calibration pattern corners.
 * @param image_pts_nrm normalized copy of image_pts, used originally for calibration.
 * @param image_pts_proj reprojected image points, calculated using calc_reprojection function.
 * @param A intrinsic matrix of the camera.
 *
 * @return
 * 2d real vector with [k1, k2] as values.
 */
cv::vec2r compute_distortion(const std::vector<std::vector<cv::vec2r>> &image_pts, const std::vector<std::vector<cv::vec2r>> &image_pts_nrm,
                             const std::vector<std::vector<cv::vec2r>> &image_pts_proj, const cv::matrixr &A);

/*!
 * @brief Draw the reprojected points, from world to image plane, using calculated camera parameters.
 *
 * Draws image points with smaller blue circle, and reprojection with larger red circles.
 *
 * @param image_pts image points from calibration pattern
 * @param image_pts_proj reprojected points calculated using calc_reprojection function
 * @param im_w image width
 * @param im_h image height
 */
cv::matrix3b draw_reprojection(const std::vector<cv::vec2r> &image_pts,
		const std::vector<cv::vec2r > &image_pts_proj, unsigned im_w, unsigned im_h, real_t scale = 1.0);

#endif /* end of include guard: CALIB_HPP_Q5H9DDXY */

<|endoftext|>


<commit_before>#include "kwm.h"

extern uint32_t MaxDisplayCount;
extern uint32_t ActiveDisplaysCount;
extern CGDirectDisplayID ActiveDisplays[];

extern std::map<int, std::vector<int> > SpacesOfWindow;
extern std::vector<screen_info> DisplayLst;
extern std::vector<window_info> WindowLst;
extern AXUIElementRef FocusedWindowRef;
extern window_info *FocusedWindow;

void GetActiveDisplays()
{
    CGGetActiveDisplayList(MaxDisplayCount, (CGDirectDisplayID*)&ActiveDisplays, &ActiveDisplaysCount);
    for(int DisplayIndex = 0; DisplayIndex < ActiveDisplaysCount; ++DisplayIndex)
    {
        CGRect DisplayRect = CGDisplayBounds(ActiveDisplays[DisplayIndex]);
        screen_info Screen;
        Screen.ID = DisplayIndex;
        Screen.X = DisplayRect.origin.x;
        Screen.Y = DisplayRect.origin.y;
        Screen.Width = DisplayRect.size.width;
        Screen.Height = DisplayRect.size.height;

        // Read from config at some point
        Screen.PaddingTop = 30;
        Screen.PaddingLeft = 20;
        Screen.PaddingRight = 20;
        Screen.PaddingBottom = 20;

        for(int Count = 0; Count < NumberOfSpaces(); ++Count)
            Screen.Space.push_back(NULL);

        DisplayLst.push_back(Screen);
    }
}

screen_info *GetDisplayOfWindow(window_info *Window)
{
    if(Window)
    {
        for(int DisplayIndex = 0; DisplayIndex < ActiveDisplaysCount; ++DisplayIndex)
        {
            screen_info *Screen = &DisplayLst[DisplayIndex];
            if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
                return Screen;
        }
    }

    return NULL;
}

std::vector<window_info*> GetAllWindowsOnDisplay(int ScreenIndex)
{
    screen_info *Screen = &DisplayLst[ScreenIndex];
    std::vector<window_info*> ScreenWindowLst;
    for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)
    {
        window_info *Window = &WindowLst[WindowIndex];
        if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
            ScreenWindowLst.push_back(Window);
    }

    return ScreenWindowLst;
}

std::vector<int> GetAllWindowIDsOnDisplay(int ScreenIndex)
{
    screen_info *Screen = &DisplayLst[ScreenIndex];
    std::vector<int> ScreenWindowIDLst;
    for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)
    {
        window_info *Window = &WindowLst[WindowIndex];
        if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
            ScreenWindowIDLst.push_back(Window->WID);
    }

    return ScreenWindowIDLst;
}

void CycleFocusedWindowDisplay(int Shift)
{
    screen_info *Screen = GetDisplayOfWindow(FocusedWindow);
    int NewScreenIndex;

    if(Shift == 1)
        NewScreenIndex = (Screen->ID + 1 >= ActiveDisplaysCount) ? 0 : Screen->ID + 1;
    else if(Shift == -1)
        NewScreenIndex = (Screen->ID - 1 < 0) ? ActiveDisplaysCount - 1 : Screen->ID - 1;
    else
        return;

    screen_info *NewScreen = &DisplayLst[NewScreenIndex];
    SetWindowDimensions(FocusedWindowRef,
            FocusedWindow,
            NewScreen->X + 30,
            NewScreen->Y + 40,
            FocusedWindow->Width,
            FocusedWindow->Height);
}
<commit_msg>separated screen paddings from windowsplit-gaps<commit_after>#include "kwm.h"

extern uint32_t MaxDisplayCount;
extern uint32_t ActiveDisplaysCount;
extern CGDirectDisplayID ActiveDisplays[];

extern std::map<int, std::vector<int> > SpacesOfWindow;
extern std::vector<screen_info> DisplayLst;
extern std::vector<window_info> WindowLst;
extern AXUIElementRef FocusedWindowRef;
extern window_info *FocusedWindow;

void GetActiveDisplays()
{
    CGGetActiveDisplayList(MaxDisplayCount, (CGDirectDisplayID*)&ActiveDisplays, &ActiveDisplaysCount);
    for(int DisplayIndex = 0; DisplayIndex < ActiveDisplaysCount; ++DisplayIndex)
    {
        CGRect DisplayRect = CGDisplayBounds(ActiveDisplays[DisplayIndex]);
        screen_info Screen;
        Screen.ID = DisplayIndex;
        Screen.X = DisplayRect.origin.x;
        Screen.Y = DisplayRect.origin.y;
        Screen.Width = DisplayRect.size.width;
        Screen.Height = DisplayRect.size.height;

        // Read from config at some point
        Screen.PaddingTop = 40;
        Screen.PaddingLeft = 20;
        Screen.PaddingRight = 20;
        Screen.PaddingBottom = 40;

        Screen.VerticalGap = 10;
        Screen.HorizontalGap = 10;

        for(int Count = 0; Count < NumberOfSpaces(); ++Count)
            Screen.Space.push_back(NULL);

        DisplayLst.push_back(Screen);
    }
}

screen_info *GetDisplayOfWindow(window_info *Window)
{
    if(Window)
    {
        for(int DisplayIndex = 0; DisplayIndex < ActiveDisplaysCount; ++DisplayIndex)
        {
            screen_info *Screen = &DisplayLst[DisplayIndex];
            if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
                return Screen;
        }
    }

    return NULL;
}

std::vector<window_info*> GetAllWindowsOnDisplay(int ScreenIndex)
{
    screen_info *Screen = &DisplayLst[ScreenIndex];
    std::vector<window_info*> ScreenWindowLst;
    for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)
    {
        window_info *Window = &WindowLst[WindowIndex];
        if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
            ScreenWindowLst.push_back(Window);
    }

    return ScreenWindowLst;
}

std::vector<int> GetAllWindowIDsOnDisplay(int ScreenIndex)
{
    screen_info *Screen = &DisplayLst[ScreenIndex];
    std::vector<int> ScreenWindowIDLst;
    for(int WindowIndex = 0; WindowIndex < WindowLst.size(); ++WindowIndex)
    {
        window_info *Window = &WindowLst[WindowIndex];
        if(Window->X >= Screen->X && Window->X <= Screen->X + Screen->Width)
            ScreenWindowIDLst.push_back(Window->WID);
    }

    return ScreenWindowIDLst;
}

void CycleFocusedWindowDisplay(int Shift)
{
    screen_info *Screen = GetDisplayOfWindow(FocusedWindow);
    int NewScreenIndex;

    if(Shift == 1)
        NewScreenIndex = (Screen->ID + 1 >= ActiveDisplaysCount) ? 0 : Screen->ID + 1;
    else if(Shift == -1)
        NewScreenIndex = (Screen->ID - 1 < 0) ? ActiveDisplaysCount - 1 : Screen->ID - 1;
    else
        return;

    screen_info *NewScreen = &DisplayLst[NewScreenIndex];
    SetWindowDimensions(FocusedWindowRef,
            FocusedWindow,
            NewScreen->X + 30,
            NewScreen->Y + 40,
            FocusedWindow->Width,
            FocusedWindow->Height);
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2009 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

// mapnik
#include <mapnik/color.hpp>
#include <mapnik/color_factory.hpp>
// boost
#include <boost/format.hpp>
// stl
#include <sstream>

namespace mapnik {

color::color( std::string const& css_string)
{
    color_factory::init_from_string(*this,css_string.c_str());
}

std::string color::to_string() const
{
    std::stringstream ss;
    if (alpha() == 255) {
        ss << "rgb("
           << red()   << ","
           << green() << ","
           << blue()  << ")";
    } else {
        ss << "rgba("
           << red()   << ","
           << green() << ","
           << blue()  << ","
           << alpha()/255.0 << ")";
    }
    return ss.str();
}

std::string color::to_hex_string() const
{
    return (boost::format("#%1$02x%2$02x%3$02x")
            % red()
            % green()
            % blue() ).str();
}
}

<commit_msg>+ catch config_error in  color::color(str) ctor<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2009 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

// mapnik
#include <mapnik/color.hpp>
#include <mapnik/color_factory.hpp>
// boost
#include <boost/format.hpp>
// stl
#include <sstream>

namespace mapnik {

color::color( std::string const& css_string)
{
    try
    {
        color_factory::init_from_string(*this,css_string.c_str());
    }
    catch (config_error const& err)
    {
        std::cerr << err.what() << std::endl;
        red_ = 0;
        green_ = 0;
        blue_ = 0;
        alpha_ = 255;
    }
}

std::string color::to_string() const
{
    std::stringstream ss;
    if (alpha() == 255) {
        ss << "rgb("
           << red()   << ","
           << green() << ","
           << blue()  << ")";
    } else {
        ss << "rgba("
           << red()   << ","
           << green() << ","
           << blue()  << ","
           << alpha()/255.0 << ")";
    }
    return ss.str();
}

std::string color::to_hex_string() const
{
    return (boost::format("#%1$02x%2$02x%3$02x")
            % red()
            % green()
            % blue() ).str();
}
}

<|endoftext|>