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

#include "../common/tutorial/tutorial.h"
#include "../common/scenegraph/obj_loader.h"
#include "../common/scenegraph/xml_loader.h"
#include "../common/tutorial/scene.h"
#include "../common/image/image.h"
#include "../common/tutorial/tutorial_device.h"

namespace embree
{
  /* name of the tutorial */
  const char* tutorialName = "viewer";

  /* configuration */
  static std::string g_rtcore = "";
  static size_t g_numThreads = 0;
  static std::string g_subdiv_mode = "";

  /* output settings */
  static size_t g_width = 512;
  static size_t g_height = 512;
  static bool g_fullscreen = false;
  static FileName outFilename = "";
  static int g_skipBenchmarkFrames = 0;
  static int g_numBenchmarkFrames = 0;
  static bool g_interactive = true;
  static bool g_anim_mode = false;
  extern "C" int g_instancing_mode = 0;
  static FileName keyframeList = "";
  static bool convert_tris_to_quads = false;
  static bool convert_bezier_to_lines = false;

  /* scene */
  TutorialScene g_obj_scene;
  Ref<SceneGraph::GroupNode> g_scene = new SceneGraph::GroupNode;
  static FileName filename = "";

  static void parseCommandLine(Ref<ParseStream> cin, const FileName& path)
  {
    while (true)
    {
      std::string tag = cin->getString();
      if (tag == "") return;

      /* parse command line parameters from a file */
      else if (tag == "-c") {
        FileName file = path + cin->getFileName();
        parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path());
      }

      /* load OBJ model*/
      else if (tag == "-i") {
        filename = path + cin->getFileName();
      }

      /* convert triangles to quads */
      else if (tag == "-convert-triangles-to-quads") {
        convert_tris_to_quads = true;
      }

      /* convert bezier to lines */
      else if (tag == "-convert-bezier-to-lines") {
        convert_bezier_to_lines = true;
      }

      /* parse camera parameters */
      else if (tag == "-vp") g_camera.from = cin->getVec3fa();
      else if (tag == "-vi") g_camera.to = cin->getVec3fa();
      else if (tag == "-vd") g_camera.to = g_camera.from + cin->getVec3fa();
      else if (tag == "-vu") g_camera.up = cin->getVec3fa();
      else if (tag == "-fov") g_camera.fov = cin->getFloat();

      /* frame buffer size */
      else if (tag == "-size") {
        g_width = cin->getInt();
        g_height = cin->getInt();
      }

      /* full screen mode */
      else if (tag == "-fullscreen")
        g_fullscreen = true;

      /* output filename */
      else if (tag == "-o") {
        outFilename = cin->getFileName();
	g_interactive = false;
      }

      else if (tag == "-objlist") {
        keyframeList = cin->getFileName();
      }

      /* subdivision mode */
      else if (tag == "-cache")
	g_subdiv_mode = ",subdiv_accel=bvh4.subdivpatch1cached";

      else if (tag == "-pregenerate")
	g_subdiv_mode = ",subdiv_accel=bvh4.grid.eager";

      else if (tag == "-anim")
	g_anim_mode = true;

      else if (tag == "-instancing") {
        std::string mode = cin->getString();
        if      (mode == "none"    ) g_instancing_mode = TutorialScene::INSTANCING_NONE;
        //else if (mode == "geometry") g_instancing_mode = TutorialScene::INSTANCING_GEOMETRY;
        else if (mode == "scene_geometry") g_instancing_mode = TutorialScene::INSTANCING_SCENE_GEOMETRY;
        else if (mode == "scene_group"   ) g_instancing_mode = TutorialScene::INSTANCING_SCENE_GROUP;
        else throw std::runtime_error("unknown instancing mode: "+mode);
      }

      /* number of frames to render in benchmark mode */
      else if (tag == "-benchmark") {
        g_skipBenchmarkFrames = cin->getInt();
        g_numBenchmarkFrames  = cin->getInt();
	g_interactive = false;
      }

      /* rtcore configuration */
      else if (tag == "-rtcore")
        g_rtcore += "," + cin->getString();

      /* number of threads to use */
      else if (tag == "-threads")
        g_numThreads = cin->getInt();

      /* ambient light source */
      else if (tag == "-ambientlight")
      {
        const Vec3fa L = cin->getVec3fa();
        g_scene->add(new SceneGraph::LightNode<AmbientLight>(AmbientLight(L)));
      }

      /* point light source */
      else if (tag == "-pointlight")
      {
        const Vec3fa P = cin->getVec3fa();
        const Vec3fa I = cin->getVec3fa();
        g_scene->add(new SceneGraph::LightNode<PointLight>(PointLight(P,I)));
      }

      /* directional light source */
      else if (tag == "-directionallight" || tag == "-dirlight")
      {
        const Vec3fa D = cin->getVec3fa();
        const Vec3fa E = cin->getVec3fa();
        g_scene->add(new SceneGraph::LightNode<DirectionalLight>(DirectionalLight(D,E)));
      }

      /* distant light source */
      else if (tag == "-distantlight")
      {
        const Vec3fa D = cin->getVec3fa();
        const Vec3fa L = cin->getVec3fa();
        const float halfAngle = cin->getFloat();
        g_scene->add(new SceneGraph::LightNode<DistantLight>(DistantLight(D,L,halfAngle)));
      }

      /* skip unknown command line parameter */
      else {
        std::cerr << "unknown command line parameter: " << tag << " ";
        while (cin->peek() != "" && cin->peek()[0] != '-') std::cerr << cin->getString() << " ";
        std::cerr << std::endl;
      }
    }
  }

  void renderBenchmark(const FileName& fileName)
  {
    resize(g_width,g_height);
    AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);

    double dt = 0.0f;
    size_t numTotalFrames = g_skipBenchmarkFrames + g_numBenchmarkFrames;
    for (size_t i=0; i<numTotalFrames; i++)
    {
      double t0 = getSeconds();
      render(0.0f,pixel2world.l.vx,pixel2world.l.vy,pixel2world.l.vz,pixel2world.p);
      double t1 = getSeconds();
      std::cout << "frame [" << i << " / " << numTotalFrames << "] ";
      std::cout << 1.0/(t1-t0) << "fps ";
      if (i < g_skipBenchmarkFrames) std::cout << "(skipped)";
      std::cout << std::endl;
      if (i >= g_skipBenchmarkFrames) dt += t1-t0;
    }
    std::cout << "frame [" << g_skipBenchmarkFrames << " - " << numTotalFrames << "] " << std::flush;
    std::cout << double(g_numBenchmarkFrames)/dt << "fps " << std::endl;
    std::cout << "BENCHMARK_RENDER " << double(g_numBenchmarkFrames)/dt << std::endl;
  }

  void renderToFile(const FileName& fileName)
  {
    resize(g_width,g_height);
    AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);
    render(0.0f,pixel2world.l.vx,pixel2world.l.vy,pixel2world.l.vz,pixel2world.p);
    void* ptr = map();
    Ref<Image> image = new Image4uc(g_width, g_height, (Col4uc*)ptr);
    storeImage(image, fileName);
    unmap();
    cleanup();
  }

  /* main function in embree namespace */
  int main(int argc, char** argv)
  {
    /* for best performance set FTZ and DAZ flags in MXCSR control and status register */
    _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
    _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);

    /* create stream for parsing */
    Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));

    /* parse command line */
    parseCommandLine(stream, FileName());

    /* load default scene if none specified */
    if (filename.ext() == "") {
      FileName file = FileName::executableFolder() + FileName("models/cornell_box.ecs");
      parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path());
    }

    /* configure number of threads */
    if (g_numThreads)
      g_rtcore += ",threads=" + toString(g_numThreads);
    if (g_numBenchmarkFrames)
      g_rtcore += ",benchmark=1";

    g_rtcore += g_subdiv_mode;

    /* load scene */
    if (toLowerCase(filename.ext()) == std::string("obj")) {
      g_scene->add(loadOBJ(filename,g_subdiv_mode != ""));
    }
    else if (toLowerCase(filename.ext()) == std::string("xml")) {
      g_scene->add(loadXML(filename,one));
    }
    else if (filename.ext() != "")
      THROW_RUNTIME_ERROR("invalid scene type: "+toLowerCase(filename.ext()));

    /* convert triangles to quads */
    if (convert_tris_to_quads)
        g_scene->triangles_to_quads();

    /* convert bezier to lines */
    if (convert_bezier_to_lines)
        g_scene->bezier_to_lines();

    /* initialize ray tracing core */
    init(g_rtcore.c_str());
    key_pressed(GLUT_KEY_F12);

    /* send model */
    g_obj_scene.add(g_scene.dynamicCast<SceneGraph::Node>(),(TutorialScene::InstancingMode)g_instancing_mode);
    g_scene = nullptr;
    set_scene(&g_obj_scene);

    /* benchmark mode */
    if (g_numBenchmarkFrames)
      renderBenchmark(outFilename);

    /* render to disk */
    if (outFilename.str() != "")
      renderToFile(outFilename);

    /* interactive mode */
    if (g_interactive) {
      initWindowState(argc,argv,tutorialName, g_width, g_height, g_fullscreen);
      enterWindowRunLoop(g_anim_mode);
    }

    return 0;
  }
}

int main(int argc, char** argv)
{
  try {
    return embree::main(argc, argv);
  }
  catch (const std::exception& e) {
    std::cout << "Error: " << e.what() << std::endl;
    return 1;
  }
  catch (...) {
    std::cout << "Error: unknown exception caught." << std::endl;
    return 1;
  }
}
<commit_msg>updates<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "../common/tutorial/tutorial.h"
#include "../common/scenegraph/obj_loader.h"
#include "../common/scenegraph/xml_loader.h"
#include "../common/tutorial/scene.h"
#include "../common/image/image.h"
#include "../common/tutorial/tutorial_device.h"

namespace embree
{
  /* name of the tutorial */
  const char* tutorialName = "viewer";

  /* configuration */
  static std::string g_rtcore = "";
  static size_t g_numThreads = 0;
  static std::string g_subdiv_mode = "";

  /* output settings */
  static size_t g_width = 512;
  static size_t g_height = 512;
  static bool g_fullscreen = false;
  static FileName outFilename = "";
  static int g_skipBenchmarkFrames = 0;
  static int g_numBenchmarkFrames = 0;
  static bool g_interactive = true;
  static bool g_anim_mode = false;
  extern "C" int g_instancing_mode = 0;
  static FileName keyframeList = "";
  static bool convert_tris_to_quads = false;
  static bool convert_bezier_to_lines = false;

  /* scene */
  TutorialScene g_obj_scene;
  Ref<SceneGraph::GroupNode> g_scene = new SceneGraph::GroupNode;
  static FileName filename = "";

  static void parseCommandLine(Ref<ParseStream> cin, const FileName& path)
  {
    while (true)
    {
      std::string tag = cin->getString();
      if (tag == "") return;

      /* parse command line parameters from a file */
      else if (tag == "-c") {
        FileName file = path + cin->getFileName();
        parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path());
      }

      /* load OBJ model*/
      else if (tag == "-i") {
        filename = path + cin->getFileName();
      }

      /* convert triangles to quads */
      else if (tag == "-convert-triangles-to-quads") {
        convert_tris_to_quads = true;
      }

      /* convert bezier to lines */
      else if (tag == "-convert-bezier-to-lines") {
        convert_bezier_to_lines = true;
      }

      /* parse camera parameters */
      else if (tag == "-vp") g_camera.from = cin->getVec3fa();
      else if (tag == "-vi") g_camera.to = cin->getVec3fa();
      else if (tag == "-vd") g_camera.to = g_camera.from + cin->getVec3fa();
      else if (tag == "-vu") g_camera.up = cin->getVec3fa();
      else if (tag == "-fov") g_camera.fov = cin->getFloat();

      /* frame buffer size */
      else if (tag == "-size") {
        g_width = cin->getInt();
        g_height = cin->getInt();
      }

      /* full screen mode */
      else if (tag == "-fullscreen")
        g_fullscreen = true;

      /* output filename */
      else if (tag == "-o") {
        outFilename = cin->getFileName();
	g_interactive = false;
      }

      else if (tag == "-objlist") {
        keyframeList = cin->getFileName();
      }

      /* subdivision mode */
      else if (tag == "-cache")
	g_subdiv_mode = ",subdiv_accel=bvh4.subdivpatch1cached";

      else if (tag == "-pregenerate")
	g_subdiv_mode = ",subdiv_accel=bvh4.grid.eager";

      else if (tag == "-anim")
	g_anim_mode = true;

      else if (tag == "-instancing") {
        std::string mode = cin->getString();
        if      (mode == "none"    ) g_instancing_mode = TutorialScene::INSTANCING_NONE;
        //else if (mode == "geometry") g_instancing_mode = TutorialScene::INSTANCING_GEOMETRY;
        else if (mode == "scene_geometry") g_instancing_mode = TutorialScene::INSTANCING_SCENE_GEOMETRY;
        else if (mode == "scene_group"   ) g_instancing_mode = TutorialScene::INSTANCING_SCENE_GROUP;
        else throw std::runtime_error("unknown instancing mode: "+mode);
      }

      /* number of frames to render in benchmark mode */
      else if (tag == "-benchmark") {
        g_skipBenchmarkFrames = cin->getInt();
        g_numBenchmarkFrames  = cin->getInt();
	g_interactive = false;
      }

      /* rtcore configuration */
      else if (tag == "-rtcore")
        g_rtcore += "," + cin->getString();

      /* number of threads to use */
      else if (tag == "-threads")
        g_numThreads = cin->getInt();

      /* ambient light source */
      else if (tag == "-ambientlight")
      {
        const Vec3fa L = cin->getVec3fa();
        g_scene->add(new SceneGraph::LightNode<AmbientLight>(AmbientLight(L)));
      }

      /* point light source */
      else if (tag == "-pointlight")
      {
        const Vec3fa P = cin->getVec3fa();
        const Vec3fa I = cin->getVec3fa();
        g_scene->add(new SceneGraph::LightNode<PointLight>(PointLight(P,I)));
      }

      /* directional light source */
      else if (tag == "-directionallight" || tag == "-dirlight")
      {
        const Vec3fa D = cin->getVec3fa();
        const Vec3fa E = cin->getVec3fa();
        g_scene->add(new SceneGraph::LightNode<DirectionalLight>(DirectionalLight(D,E)));
      }

      /* distant light source */
      else if (tag == "-distantlight")
      {
        const Vec3fa D = cin->getVec3fa();
        const Vec3fa L = cin->getVec3fa();
        const float halfAngle = cin->getFloat();
        g_scene->add(new SceneGraph::LightNode<DistantLight>(DistantLight(D,L,halfAngle)));
      }

      /* skip unknown command line parameter */
      else {
        std::cerr << "unknown command line parameter: " << tag << " ";
        while (cin->peek() != "" && cin->peek()[0] != '-') std::cerr << cin->getString() << " ";
        std::cerr << std::endl;
      }
    }
  }

  void renderBenchmark(const FileName& fileName)
  {
    resize(g_width,g_height);
    AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);

    double dt = 0.0f;
    size_t numTotalFrames = g_skipBenchmarkFrames + g_numBenchmarkFrames;
    for (size_t i=0; i<numTotalFrames; i++)
    {
      double t0 = getSeconds();
      render(0.0f,pixel2world.l.vx,pixel2world.l.vy,pixel2world.l.vz,pixel2world.p);
      double t1 = getSeconds();
      std::cout << "frame [" << i << " / " << numTotalFrames << "] ";
      std::cout << 1.0/(t1-t0) << "fps ";
      if (i < g_skipBenchmarkFrames) std::cout << "(skipped)";
      std::cout << std::endl;
      if (i >= g_skipBenchmarkFrames) dt += t1-t0;
    }
    std::cout << "frame [" << g_skipBenchmarkFrames << " - " << numTotalFrames << "] " << std::flush;
    std::cout << double(g_numBenchmarkFrames)/dt << "fps " << std::endl;
    std::cout << "BENCHMARK_RENDER " << double(g_numBenchmarkFrames)/dt << std::endl;
  }

  void renderToFile(const FileName& fileName)
  {
    resize(g_width,g_height);
    AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);
    render(0.0f,pixel2world.l.vx,pixel2world.l.vy,pixel2world.l.vz,pixel2world.p);
    void* ptr = map();
    Ref<Image> image = new Image4uc(g_width, g_height, (Col4uc*)ptr);
    storeImage(image, fileName);
    unmap();
    cleanup();
  }

  /* main function in embree namespace */
  int main(int argc, char** argv)
  {
    /* for best performance set FTZ and DAZ flags in MXCSR control and status register */
    _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
    _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);

    /* create stream for parsing */
    Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));

    /* parse command line */
    parseCommandLine(stream, FileName());

    /* load default scene if none specified */
    if (filename.ext() == "") {
      FileName file = FileName::executableFolder() + FileName("models/cornell_box.ecs");
      parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path());
    }

    /* configure number of threads */
    if (g_numThreads)
      g_rtcore += ",threads=" + toString(g_numThreads);
    if (g_numBenchmarkFrames)
      g_rtcore += ",benchmark=1";

    g_rtcore += g_subdiv_mode;

    /* load scene */
    if (toLowerCase(filename.ext()) == std::string("obj")) {
      g_scene->add(loadOBJ(filename,g_subdiv_mode != ""));
    }
    else if (toLowerCase(filename.ext()) == std::string("xml")) {
      g_scene->add(loadXML(filename,one));
    }
    else if (filename.ext() != "")
      THROW_RUNTIME_ERROR("invalid scene type: "+toLowerCase(filename.ext()));

    /* convert triangles to quads */
    if (convert_tris_to_quads)
        g_scene->triangles_to_quads();

    /* convert bezier to lines */
    if (convert_bezier_to_lines)
        g_scene->bezier_to_lines();

    /* initialize ray tracing core */
    init(g_rtcore.c_str());

    /* send model */
    g_obj_scene.add(g_scene.dynamicCast<SceneGraph::Node>(),(TutorialScene::InstancingMode)g_instancing_mode);
    g_scene = nullptr;
    set_scene(&g_obj_scene);

    /* benchmark mode */
    if (g_numBenchmarkFrames)
      renderBenchmark(outFilename);

    /* render to disk */
    if (outFilename.str() != "")
      renderToFile(outFilename);

    /* interactive mode */
    if (g_interactive) {
      initWindowState(argc,argv,tutorialName, g_width, g_height, g_fullscreen);
      enterWindowRunLoop(g_anim_mode);
    }

    return 0;
  }
}

int main(int argc, char** argv)
{
  try {
    return embree::main(argc, argv);
  }
  catch (const std::exception& e) {
    std::cout << "Error: " << e.what() << std::endl;
    return 1;
  }
  catch (...) {
    std::cout << "Error: unknown exception caught." << std::endl;
    return 1;
  }
}
<|endoftext|>


<commit_before>/*
 * PlyPublisher.cpp
 *
 *  Created on: Aug 7, 2013
 *      Author: Péter Fankhauser
 *   Institute: ETH Zurich, Autonomous Systems Lab
 */

#include "ply_publisher/PlyPublisher.hpp"

//PCL
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/ply_io.h>
#include <pcl_conversions/pcl_conversions.h>
// define the following in order to eliminate the deprecated headers warning
#define VTK_EXCLUDE_STRSTREAM_HEADERS
#include <pcl/io/vtk_lib_io.h>

using namespace std;
using namespace ros;
using namespace pcl;
using namespace pcl::io;
using namespace pcl_conversions;

namespace ply_publisher {

PlyPublisher::PlyPublisher(ros::NodeHandle& nodeHandle)
    : nodeHandle_(nodeHandle),
      pointCloudMessage_(new sensor_msgs::PointCloud2)
{
  if (!readParameters()) ros::requestShutdown();
  pointCloudPublisher_ = nodeHandle_.advertise<sensor_msgs::PointCloud2>(pointCloudTopic_, 1, true);
  initialize();
}

PlyPublisher::~PlyPublisher()
{

}

bool PlyPublisher::readParameters()
{
  bool allParametersRead = true;
  if (!nodeHandle_.getParam("file_path", filePath_)) allParametersRead = false;
  if (!nodeHandle_.getParam("topic", pointCloudTopic_)) allParametersRead = false;
  if (!nodeHandle_.getParam("frame", pointCloudFrameId_)) allParametersRead = false;

  double updateRate;
  nodeHandle_.param("rate", updateRate, 0.0);
  if (updateRate == 0.0)
  {
    isContinousPublishing_ = false;
  }
  else
  {
    isContinousPublishing_ = true;
    updateDuration_.fromSec(1.0 / updateRate);
  }

  if (!allParametersRead)
  {
    ROS_WARN("Could not read all parameters. Typical command-line usage:\n rosrun ply_publisher ply_publisher"
        " _file_path:=path_to_your_point_cloud_file _topic:=/your_topic _frame:=point_cloud_frame"
        " (optional) _rate:=publishing_rate");
    return false;
  }

  return true;
}

void PlyPublisher::initialize()
{
  if (!readFile(filePath_, pointCloudFrameId_)) ros::requestShutdown();

  if (isContinousPublishing_)
  {
    timer_ = nodeHandle_.createTimer(updateDuration_, &PlyPublisher::timerCallback, this);
  }
  else
  {
    Duration(1.0).sleep(); // Need this to get things ready before publishing.
    if (!publish()) ROS_ERROR("Something went wrong when trying to read and publish the point cloud file.");
    ros::requestShutdown();
  }
}

bool PlyPublisher::readFile(const std::string& filePath, const std::string& pointCloudFrameId)
{
  if (filePath.find(".ply") != std::string::npos) {
    // Load .ply file.
    PointCloud<PointXYZINormal> pointCloud;
    if (loadPLYFile(filePath, pointCloud) != 0) return false;

    // Define PointCloud2 message.
    toROSMsg(pointCloud, *pointCloudMessage_);
  }
  else if (filePath.find(".vtk") != std::string::npos) {
    // Load .vtk file.
    PolygonMesh polygonMesh;
    loadPolygonFileVTK(filePath, polygonMesh);

    // Define PointCloud2 message.
    moveFromPCL(polygonMesh.cloud, *pointCloudMessage_);
  }
  else
  {
    ROS_ERROR_STREAM("Data format not supported.");
    return false;
  }

  pointCloudMessage_->header.frame_id = pointCloudFrameId;

  ROS_INFO_STREAM("Loaded point cloud with " << pointCloudMessage_->width << " points.");
  return true;
}

void PlyPublisher::timerCallback(const ros::TimerEvent& timerEvent)
{
  if (!publish()) ROS_ERROR("Something went wrong when trying to read and publish the point cloud file.");
}

bool PlyPublisher::publish()
{
  pointCloudMessage_->header.stamp = Time::now();
  if (pointCloudPublisher_.getNumSubscribers() > 0u)
  {
    pointCloudPublisher_.publish(pointCloudMessage_);
    ROS_INFO_STREAM("Point cloud published in topic \"" << pointCloudTopic_ << "\".");
  }
  return true;
}

} /* namespace */
<commit_msg>Now reading RGB values.<commit_after>/*
 * PlyPublisher.cpp
 *
 *  Created on: Aug 7, 2013
 *      Author: Péter Fankhauser
 *   Institute: ETH Zurich, Autonomous Systems Lab
 */

#include "ply_publisher/PlyPublisher.hpp"

//PCL
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/ply_io.h>
#include <pcl_conversions/pcl_conversions.h>
// define the following in order to eliminate the deprecated headers warning
#define VTK_EXCLUDE_STRSTREAM_HEADERS
#include <pcl/io/vtk_lib_io.h>

using namespace std;
using namespace ros;
using namespace pcl;
using namespace pcl::io;
using namespace pcl_conversions;

namespace ply_publisher {

PlyPublisher::PlyPublisher(ros::NodeHandle& nodeHandle)
    : nodeHandle_(nodeHandle),
      pointCloudMessage_(new sensor_msgs::PointCloud2)
{
  if (!readParameters()) ros::requestShutdown();
  pointCloudPublisher_ = nodeHandle_.advertise<sensor_msgs::PointCloud2>(pointCloudTopic_, 1, true);
  initialize();
}

PlyPublisher::~PlyPublisher()
{

}

bool PlyPublisher::readParameters()
{
  bool allParametersRead = true;
  if (!nodeHandle_.getParam("file_path", filePath_)) allParametersRead = false;
  if (!nodeHandle_.getParam("topic", pointCloudTopic_)) allParametersRead = false;
  if (!nodeHandle_.getParam("frame", pointCloudFrameId_)) allParametersRead = false;

  double updateRate;
  nodeHandle_.param("rate", updateRate, 0.0);
  if (updateRate == 0.0)
  {
    isContinousPublishing_ = false;
  }
  else
  {
    isContinousPublishing_ = true;
    updateDuration_.fromSec(1.0 / updateRate);
  }

  if (!allParametersRead)
  {
    ROS_WARN("Could not read all parameters. Typical command-line usage:\n rosrun ply_publisher ply_publisher"
        " _file_path:=path_to_your_point_cloud_file _topic:=/your_topic _frame:=point_cloud_frame"
        " (optional) _rate:=publishing_rate");
    return false;
  }

  return true;
}

void PlyPublisher::initialize()
{
  if (!readFile(filePath_, pointCloudFrameId_)) ros::requestShutdown();

  if (isContinousPublishing_)
  {
    timer_ = nodeHandle_.createTimer(updateDuration_, &PlyPublisher::timerCallback, this);
  }
  else
  {
    Duration(1.0).sleep(); // Need this to get things ready before publishing.
    if (!publish()) ROS_ERROR("Something went wrong when trying to read and publish the point cloud file.");
    ros::requestShutdown();
  }
}

bool PlyPublisher::readFile(const std::string& filePath, const std::string& pointCloudFrameId)
{
  if (filePath.find(".ply") != std::string::npos) {
    // Load .ply file.
    PointCloud<PointXYZRGBNormal> pointCloud;
    if (loadPLYFile(filePath, pointCloud) != 0) return false;

    // Define PointCloud2 message.
    toROSMsg(pointCloud, *pointCloudMessage_);
  }
  else if (filePath.find(".vtk") != std::string::npos) {
    // Load .vtk file.
    PolygonMesh polygonMesh;
    loadPolygonFileVTK(filePath, polygonMesh);

    // Define PointCloud2 message.
    moveFromPCL(polygonMesh.cloud, *pointCloudMessage_);
  }
  else
  {
    ROS_ERROR_STREAM("Data format not supported.");
    return false;
  }

  pointCloudMessage_->header.frame_id = pointCloudFrameId;

  ROS_INFO_STREAM("Loaded point cloud with " << pointCloudMessage_->width << " points.");
  return true;
}

void PlyPublisher::timerCallback(const ros::TimerEvent& timerEvent)
{
  if (!publish()) ROS_ERROR("Something went wrong when trying to read and publish the point cloud file.");
}

bool PlyPublisher::publish()
{
  pointCloudMessage_->header.stamp = Time::now();
  if (pointCloudPublisher_.getNumSubscribers() > 0u)
  {
    pointCloudPublisher_.publish(pointCloudMessage_);
    ROS_INFO_STREAM("Point cloud published in topic \"" << pointCloudTopic_ << "\".");
  }
  return true;
}

} /* namespace */
<|endoftext|>


<commit_before>#include <iostream>
#include <QPainter>
#include <QPaintEvent>
#include <QColorDialog>
#include <QToolTip>
#include "PaletteWidget.h"

#define CBOX_W 40
#define CBOX_H 40
#define CBOX_AX m_cboxX
#define CBOX_AY   5
#define CBOX_PX (25+m_cboxX)
#define CBOX_PY  30

#define HR_Y 75

#define PAL_X m_palX
#define PAL_Y 85
#define PAL_NX 16
#define PAL_NY 16
#define PBOX_W m_pboxW
#define PBOX_H m_pboxH

QSize PaletteWidget::minimumSizeHint() const
{
  return QSize(100, PAL_Y+PAL_NY*8+8/2);
}

QSize PaletteWidget::sizeHint() const
{
  return QSize(100, PAL_Y+PAL_NY*PBOX_H+PBOX_H/2);
}

void PaletteWidget::resizeEvent(QResizeEvent *event)
{
  int w=event->size().width();
  int h=event->size().height();

  m_pboxW=(w-5*2)/PAL_NX;
  m_pboxH=(h-PAL_Y-5)/PAL_NY;

  if (m_pboxW<2) m_pboxW=2;
  if (m_pboxH<2) m_pboxH=2;

  m_palX=(w-m_pboxW*PAL_NX)/2;

  m_cboxX=(w-(CBOX_PX-m_cboxX+CBOX_W))/2;

  //printf("palette box: %dx%d\n", m_pboxW, m_pboxH);
}

QRect PaletteWidget::palRect(int index) const
{
  if (index<0) return QRect();

  int x=PAL_X+(index%PAL_NX)*PBOX_W;
  int y=PAL_Y+(index/PAL_NX)*PBOX_H;
  return QRect(x, y, PBOX_W, PBOX_H);
}

QColor PaletteWidget::toQColor(const Imath::Color4f& in)
{
    return QColor((int)(in.r * 255.0f),
                  (int)(in.g * 255.0f),
                  (int)(in.b * 255.0f),
                  (int)(in.a * 255.0f));
}

QColor PaletteWidget::toQColor(const Imath::Color4f& in, float a)
{
    return QColor((int)(in.r * 255.0f),
                  (int)(in.g * 255.0f),
                  (int)(in.b * 255.0f),
                  (int)(   a * 255.0f));
}

Imath::Color4f PaletteWidget::toColor4f(QColor c)
{
  return Imath::Color4f(
    c.red  ()/255.0f,
    c.green()/255.0f,
    c.blue ()/255.0f,
    c.alpha()/255.0f);
}

void PaletteWidget::setPalette(ColorPalettePtr pal)
{
  m_palette=pal;
  update();
}

bool PaletteWidget::event(QEvent *event)
{
  if (event->type()==QEvent::ToolTip)
  {
    const QHelpEvent &he=*(QHelpEvent*)event;
    int ci=clickHit(he.pos());

    if (ci<0 || !m_palette)
    {
      QToolTip::hideText();
      event->ignore();
    }
    else
    {
      SproxelColor c=m_palette->color(ci);
      QToolTip::showText(he.globalPos(),
        QString("%1 (#%2): #%3\nR:%4 G:%5 B:%6 A:%7").arg(ci).arg(ci, 2, 16, QChar('0'))
          .arg(toQColor(c).rgba(), 8, 16, QChar('0'))
          .arg(int(c.r*255)).arg(int(c.g*255)).arg(int(c.b*255)).arg(int(c.a*255)),
        this, palRect(ci));
    }

    return true;
  }

  return QWidget::event(event);
}

void PaletteWidget::paintEvent(QPaintEvent*)
{
  QPainter painter(this);

  // Some useful colors|tools
  Imath::Color4f brighterBackground = m_backgroundColor * 1.05f;
  brighterBackground.a = 1.0f;
  QPen brighterBackgroundPen = QPen(toQColor(brighterBackground));

  // BG clear
  painter.fillRect(0, 0, width(), height(), QBrush(toQColor(m_backgroundColor)));

  // Active and passive colors get drawn in the upper-left
  painter.fillRect(CBOX_PX  , CBOX_PY  , CBOX_W  , CBOX_H  , QBrush(QColor(0,0,0)));
  painter.fillRect(CBOX_PX+1, CBOX_PY+1, CBOX_W-2, CBOX_H-2, QBrush(QColor(255, 255, 255)));
  painter.fillRect(CBOX_PX+2, CBOX_PY+2, CBOX_W-4, CBOX_H-4, QBrush(toQColor(m_passiveColor, 1)));

  painter.fillRect(CBOX_AX  , CBOX_AY  , CBOX_W  , CBOX_H  , QBrush(QColor(0,0,0)));
  painter.fillRect(CBOX_AX+1, CBOX_AY+1, CBOX_W-2, CBOX_H-2, QBrush(QColor(255, 255, 255)));
  painter.fillRect(CBOX_AX+2, CBOX_AY+2, CBOX_W-4, CBOX_H-4, QBrush(toQColor(m_activeColor, 1)));

  // Horizontal rule
  painter.setPen(brighterBackgroundPen);
  painter.drawLine(QPoint(0, HR_Y), QPoint(width(), HR_Y));

  // Palette grid
  if (m_palette)
  {
    for (int y=0; y<PAL_NY; ++y)
      for (int x=0; x<PAL_NX; ++x)
      {
        Imath::Color4f c=m_palette->color(y*PAL_NX+x);
        painter.fillRect(PAL_X+x*PBOX_W, PAL_Y+y*PBOX_H, PBOX_W, PBOX_H, toQColor(c, 1));
      }

    if (m_hilightIndex>=0)
    {
      int x=PAL_X+(m_hilightIndex%PAL_NX)*PBOX_W;
      int y=PAL_Y+(m_hilightIndex/PAL_NX)*PBOX_H;
      painter.fillRect(x  , y  , PBOX_W  , PBOX_H  , QColor(0, 0, 0));
      painter.fillRect(x+1, y+1, PBOX_W-2, PBOX_H-2, QColor(255, 255, 255));
      painter.fillRect(x+2, y+2, PBOX_W-4, PBOX_H-4, toQColor(m_palette->color(m_hilightIndex), 1));
    }

    if (m_activeIndex>=0)
    {
      int x=PAL_X+(m_activeIndex%PAL_NX)*PBOX_W;
      int y=PAL_Y+(m_activeIndex/PAL_NX)*PBOX_H;
      painter.fillRect(x+PBOX_W/4, y+PBOX_H/2, PBOX_W/2, 1, toQColor(SproxelColor(1)-m_activeColor, 1));
      painter.fillRect(x+PBOX_W/2, y+PBOX_H/4, 1, PBOX_H/2, toQColor(SproxelColor(1)-m_activeColor, 1));
    }

    /*
    if (m_passiveIndex>=0)
    {
      int x=PAL_X+(m_passiveIndex%PAL_NX)*PBOX_W;
      int y=PAL_Y+(m_passiveIndex/PAL_NX)*PBOX_H;
      painter.fillRect(x+PBOX_W/4, y+PBOX_H/2, PBOX_W/2, 1, toQColor(SproxelColor(1)-m_passiveColor, 1));
    }
    */
  }
}

void PaletteWidget::mousePressEvent(QMouseEvent* event)
{
  QColor color;

  int ci=clickHit(event->pos());

  setHilight(ci);

  switch(ci)
  {
    case HIT_NONE:
      break;

    case HIT_ACTIVE_COLOR_BOX:
      color = QColorDialog::getColor(toQColor(m_activeColor), this,
        "Select active color", QColorDialog::ShowAlphaChannel);

      if (color.isValid()) setActiveColor(toColor4f(color), -1);
      break;

    case HIT_PASSIVE_COLOR_BOX:
      color = QColorDialog::getColor(toQColor(m_passiveColor), this,
        "Select passive color", QColorDialog::ShowAlphaChannel);

      if (color.isValid()) setPassiveColor(toColor4f(color), -1);
      break;

    default:
      if (event->button()==Qt::LeftButton)
      {
        if (m_palette) setActiveColor(m_palette->color(ci), ci);
      }
      else if (event->button()==Qt::RightButton)
      {
        if (m_palette)
        {
          color = QColorDialog::getColor(toQColor(m_palette->color(ci)), this,
            QString("Select palette color %1 (#%2)").arg(ci).arg(ci, 2, 16, QChar('0')),
            QColorDialog::ShowAlphaChannel);

          if (color.isValid()) p_undoManager->setPaletteColor(m_palette, ci, toColor4f(color));
        }
      }
      break;
  }
}

void PaletteWidget::mouseMoveEvent(QMouseEvent* event)
{
  setHilight(clickHit(event->pos()));
}

void PaletteWidget::setHilight(int ci)
{
  if (m_hilightIndex!=ci)
  {
    int oldIndex=m_hilightIndex;
    m_hilightIndex=ci;
    repaint(palRect(oldIndex));
    repaint(palRect(ci));
  }
}

void PaletteWidget::mouseDoubleClickEvent(QMouseEvent* /*event*/)
{
  // Emit palette changed signal
  // emit activeColorChanged(Imath::Color4f(1.0f, 0.0f, 1.0f, 1.0f));

  //std::cout << event->pos().x() << " " << event->pos().y() << std::endl;
  //std::cout << clickHit(event->pos()) << std::endl;
}

void PaletteWidget::leaveEvent(QEvent *)
{
  setHilight(HIT_NONE);
}

int PaletteWidget::clickHit(const QPoint& p)
{
  if (p.x() >= CBOX_AX && p.y() >= CBOX_AY && p.x() < CBOX_AX+CBOX_W && p.y() < CBOX_AY+CBOX_H)
    return HIT_ACTIVE_COLOR_BOX;
  else if (p.x() >= CBOX_PX && p.y() >= CBOX_PY && p.x() < CBOX_PX+CBOX_W && p.y() < CBOX_PY+CBOX_H)
    return HIT_PASSIVE_COLOR_BOX;

  int nx=p.x()-PAL_X, ny=p.y()-PAL_Y;
  if (nx>=0 && ny>=0)
  {
    nx/=PBOX_W;
    ny/=PBOX_H;
    if (nx<PAL_NX && ny<PAL_NY) return ny*PAL_NX+nx;
  }

  return HIT_NONE;
}

void PaletteWidget::setActiveColor(const Imath::Color4f& color, int index)
{
    int oldIndex=m_activeIndex;
    m_activeColor = color;
    m_activeIndex = index;
    emit activeColorChanged(m_activeColor, m_activeIndex);
    repaint(0, 0, width(), HR_Y);
    repaint(palRect(oldIndex));
    repaint(palRect(m_activeIndex));
}

void PaletteWidget::setPassiveColor(const Imath::Color4f& color, int index)
{
    int oldIndex=m_passiveIndex;
    m_passiveColor = color;
    m_passiveIndex = index;
    //emit activeColorChanged(m_activeColor);
    repaint(0, 0, width(), HR_Y);
    repaint(palRect(oldIndex));
    repaint(palRect(m_passiveIndex));
}

void PaletteWidget::swapColors()
{
    Imath::Color4f copy = m_activeColor; m_activeColor = m_passiveColor; m_passiveColor = copy;
    int            icpy = m_activeIndex; m_activeIndex = m_passiveIndex; m_passiveIndex = icpy;
    emit activeColorChanged(m_activeColor, m_activeIndex);
    repaint(0, 0, width(), HR_Y);
    repaint(palRect(m_activeIndex));
    repaint(palRect(m_passiveIndex));
}
<commit_msg>Palette now maintains 1:1 aspect ratio<commit_after>#include <iostream>
#include <QPainter>
#include <QPaintEvent>
#include <QColorDialog>
#include <QToolTip>
#include "PaletteWidget.h"

#define CBOX_W 40
#define CBOX_H 40
#define CBOX_AX m_cboxX
#define CBOX_AY   5
#define CBOX_PX (25+m_cboxX)
#define CBOX_PY  30

#define HR_Y 75

#define PAL_X m_palX
#define PAL_Y 85
#define PAL_NX 16
#define PAL_NY 16
#define PBOX_W m_pboxW
#define PBOX_H m_pboxH

QSize PaletteWidget::minimumSizeHint() const
{
  return QSize(100, PAL_Y+PAL_NY*8+8/2);
}

QSize PaletteWidget::sizeHint() const
{
  return QSize(100, PAL_Y+PAL_NY*PBOX_H+PBOX_H/2);
}

void PaletteWidget::resizeEvent(QResizeEvent *event)
{
  int w=event->size().width();
  int h=event->size().height();

  m_pboxW=(w-5*2)/PAL_NX;
  if (m_pboxW<2) m_pboxW=2;
  m_pboxH=m_pboxW;

  m_palX=(w-m_pboxW*PAL_NX)/2;

  m_cboxX=(w-(CBOX_PX-m_cboxX+CBOX_W))/2;

  //printf("palette box: %dx%d\n", m_pboxW, m_pboxH);
}

QRect PaletteWidget::palRect(int index) const
{
  if (index<0) return QRect();

  int x=PAL_X+(index%PAL_NX)*PBOX_W;
  int y=PAL_Y+(index/PAL_NX)*PBOX_H;
  return QRect(x, y, PBOX_W, PBOX_H);
}

QColor PaletteWidget::toQColor(const Imath::Color4f& in)
{
    return QColor((int)(in.r * 255.0f),
                  (int)(in.g * 255.0f),
                  (int)(in.b * 255.0f),
                  (int)(in.a * 255.0f));
}

QColor PaletteWidget::toQColor(const Imath::Color4f& in, float a)
{
    return QColor((int)(in.r * 255.0f),
                  (int)(in.g * 255.0f),
                  (int)(in.b * 255.0f),
                  (int)(   a * 255.0f));
}

Imath::Color4f PaletteWidget::toColor4f(QColor c)
{
  return Imath::Color4f(
    c.red  ()/255.0f,
    c.green()/255.0f,
    c.blue ()/255.0f,
    c.alpha()/255.0f);
}

void PaletteWidget::setPalette(ColorPalettePtr pal)
{
  m_palette=pal;
  update();
}

bool PaletteWidget::event(QEvent *event)
{
  if (event->type()==QEvent::ToolTip)
  {
    const QHelpEvent &he=*(QHelpEvent*)event;
    int ci=clickHit(he.pos());

    if (ci<0 || !m_palette)
    {
      QToolTip::hideText();
      event->ignore();
    }
    else
    {
      SproxelColor c=m_palette->color(ci);
      QToolTip::showText(he.globalPos(),
        QString("%1 (#%2): #%3\nR:%4 G:%5 B:%6 A:%7").arg(ci).arg(ci, 2, 16, QChar('0'))
          .arg(toQColor(c).rgba(), 8, 16, QChar('0'))
          .arg(int(c.r*255)).arg(int(c.g*255)).arg(int(c.b*255)).arg(int(c.a*255)),
        this, palRect(ci));
    }

    return true;
  }

  return QWidget::event(event);
}

void PaletteWidget::paintEvent(QPaintEvent*)
{
  QPainter painter(this);

  // Some useful colors|tools
  Imath::Color4f brighterBackground = m_backgroundColor * 1.05f;
  brighterBackground.a = 1.0f;
  QPen brighterBackgroundPen = QPen(toQColor(brighterBackground));

  // BG clear
  painter.fillRect(0, 0, width(), height(), QBrush(toQColor(m_backgroundColor)));

  // Active and passive colors get drawn in the upper-left
  painter.fillRect(CBOX_PX  , CBOX_PY  , CBOX_W  , CBOX_H  , QBrush(QColor(0,0,0)));
  painter.fillRect(CBOX_PX+1, CBOX_PY+1, CBOX_W-2, CBOX_H-2, QBrush(QColor(255, 255, 255)));
  painter.fillRect(CBOX_PX+2, CBOX_PY+2, CBOX_W-4, CBOX_H-4, QBrush(toQColor(m_passiveColor, 1)));

  painter.fillRect(CBOX_AX  , CBOX_AY  , CBOX_W  , CBOX_H  , QBrush(QColor(0,0,0)));
  painter.fillRect(CBOX_AX+1, CBOX_AY+1, CBOX_W-2, CBOX_H-2, QBrush(QColor(255, 255, 255)));
  painter.fillRect(CBOX_AX+2, CBOX_AY+2, CBOX_W-4, CBOX_H-4, QBrush(toQColor(m_activeColor, 1)));

  // Horizontal rule
  painter.setPen(brighterBackgroundPen);
  painter.drawLine(QPoint(0, HR_Y), QPoint(width(), HR_Y));

  // Palette grid
  if (m_palette)
  {
    for (int y=0; y<PAL_NY; ++y)
      for (int x=0; x<PAL_NX; ++x)
      {
        Imath::Color4f c=m_palette->color(y*PAL_NX+x);
        painter.fillRect(PAL_X+x*PBOX_W, PAL_Y+y*PBOX_H, PBOX_W, PBOX_H, toQColor(c, 1));
      }

    if (m_hilightIndex>=0)
    {
      int x=PAL_X+(m_hilightIndex%PAL_NX)*PBOX_W;
      int y=PAL_Y+(m_hilightIndex/PAL_NX)*PBOX_H;
      painter.fillRect(x  , y  , PBOX_W  , PBOX_H  , QColor(0, 0, 0));
      painter.fillRect(x+1, y+1, PBOX_W-2, PBOX_H-2, QColor(255, 255, 255));
      painter.fillRect(x+2, y+2, PBOX_W-4, PBOX_H-4, toQColor(m_palette->color(m_hilightIndex), 1));
    }

    if (m_activeIndex>=0)
    {
      int x=PAL_X+(m_activeIndex%PAL_NX)*PBOX_W;
      int y=PAL_Y+(m_activeIndex/PAL_NX)*PBOX_H;
      painter.fillRect(x+PBOX_W/4, y+PBOX_H/2, PBOX_W/2, 1, toQColor(SproxelColor(1)-m_activeColor, 1));
      painter.fillRect(x+PBOX_W/2, y+PBOX_H/4, 1, PBOX_H/2, toQColor(SproxelColor(1)-m_activeColor, 1));
    }

    /*
    if (m_passiveIndex>=0)
    {
      int x=PAL_X+(m_passiveIndex%PAL_NX)*PBOX_W;
      int y=PAL_Y+(m_passiveIndex/PAL_NX)*PBOX_H;
      painter.fillRect(x+PBOX_W/4, y+PBOX_H/2, PBOX_W/2, 1, toQColor(SproxelColor(1)-m_passiveColor, 1));
    }
    */
  }
}

void PaletteWidget::mousePressEvent(QMouseEvent* event)
{
  QColor color;

  int ci=clickHit(event->pos());

  setHilight(ci);

  switch(ci)
  {
    case HIT_NONE:
      break;

    case HIT_ACTIVE_COLOR_BOX:
      color = QColorDialog::getColor(toQColor(m_activeColor), this,
        "Select active color", QColorDialog::ShowAlphaChannel);

      if (color.isValid()) setActiveColor(toColor4f(color), -1);
      break;

    case HIT_PASSIVE_COLOR_BOX:
      color = QColorDialog::getColor(toQColor(m_passiveColor), this,
        "Select passive color", QColorDialog::ShowAlphaChannel);

      if (color.isValid()) setPassiveColor(toColor4f(color), -1);
      break;

    default:
      if (event->button()==Qt::LeftButton)
      {
        if (m_palette) setActiveColor(m_palette->color(ci), ci);
      }
      else if (event->button()==Qt::RightButton)
      {
        if (m_palette)
        {
          color = QColorDialog::getColor(toQColor(m_palette->color(ci)), this,
            QString("Select palette color %1 (#%2)").arg(ci).arg(ci, 2, 16, QChar('0')),
            QColorDialog::ShowAlphaChannel);

          if (color.isValid()) p_undoManager->setPaletteColor(m_palette, ci, toColor4f(color));
        }
      }
      break;
  }
}

void PaletteWidget::mouseMoveEvent(QMouseEvent* event)
{
  setHilight(clickHit(event->pos()));
}

void PaletteWidget::setHilight(int ci)
{
  if (m_hilightIndex!=ci)
  {
    int oldIndex=m_hilightIndex;
    m_hilightIndex=ci;
    repaint(palRect(oldIndex));
    repaint(palRect(ci));
  }
}

void PaletteWidget::mouseDoubleClickEvent(QMouseEvent* /*event*/)
{
  // Emit palette changed signal
  // emit activeColorChanged(Imath::Color4f(1.0f, 0.0f, 1.0f, 1.0f));

  //std::cout << event->pos().x() << " " << event->pos().y() << std::endl;
  //std::cout << clickHit(event->pos()) << std::endl;
}

void PaletteWidget::leaveEvent(QEvent *)
{
  setHilight(HIT_NONE);
}

int PaletteWidget::clickHit(const QPoint& p)
{
  if (p.x() >= CBOX_AX && p.y() >= CBOX_AY && p.x() < CBOX_AX+CBOX_W && p.y() < CBOX_AY+CBOX_H)
    return HIT_ACTIVE_COLOR_BOX;
  else if (p.x() >= CBOX_PX && p.y() >= CBOX_PY && p.x() < CBOX_PX+CBOX_W && p.y() < CBOX_PY+CBOX_H)
    return HIT_PASSIVE_COLOR_BOX;

  int nx=p.x()-PAL_X, ny=p.y()-PAL_Y;
  if (nx>=0 && ny>=0)
  {
    nx/=PBOX_W;
    ny/=PBOX_H;
    if (nx<PAL_NX && ny<PAL_NY) return ny*PAL_NX+nx;
  }

  return HIT_NONE;
}

void PaletteWidget::setActiveColor(const Imath::Color4f& color, int index)
{
    int oldIndex=m_activeIndex;
    m_activeColor = color;
    m_activeIndex = index;
    emit activeColorChanged(m_activeColor, m_activeIndex);
    repaint(0, 0, width(), HR_Y);
    repaint(palRect(oldIndex));
    repaint(palRect(m_activeIndex));
}

void PaletteWidget::setPassiveColor(const Imath::Color4f& color, int index)
{
    int oldIndex=m_passiveIndex;
    m_passiveColor = color;
    m_passiveIndex = index;
    //emit activeColorChanged(m_activeColor);
    repaint(0, 0, width(), HR_Y);
    repaint(palRect(oldIndex));
    repaint(palRect(m_passiveIndex));
}

void PaletteWidget::swapColors()
{
    Imath::Color4f copy = m_activeColor; m_activeColor = m_passiveColor; m_passiveColor = copy;
    int            icpy = m_activeIndex; m_activeIndex = m_passiveIndex; m_passiveIndex = icpy;
    emit activeColorChanged(m_activeColor, m_activeIndex);
    repaint(0, 0, width(), HR_Y);
    repaint(palRect(m_activeIndex));
    repaint(palRect(m_passiveIndex));
}
<|endoftext|>


<commit_before>/*
 * kdenlivetitle_wrapper.cpp -- kdenlivetitle wrapper
 * Copyright (c) 2009 Marco Gittler <g.marco@freenet.de>
 *
 * 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 Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <QtGui/QImage>
#include <QtGui/QPainter>
#include <QtCore/QCoreApplication>
#include <QtGui/QApplication>
#include <QtCore/QDebug>
#include <QtCore/QFile>
#include <QtGui/QGraphicsView>
#include <QtGui/QGraphicsScene>
#include <QtGui/QGraphicsTextItem>
#include <QtGui/QtextCursor>
#include "kdenlivetitle_wrapper.h"
#include <framework/mlt_producer.h>
extern "C" {
void init_qt (const char* c){
    titleclass=new Title(QString(c));
}
void refresh_kdenlivetitle( void* buffer, int width, int height , double position){
   titleclass->drawKdenliveTitle(buffer,width,height,position);
   int i=0;
   unsigned char* pointer;
   //rotate bytes for correct order in mlt
   for (i=0;i<width*height*4;i+=4){
        pointer=(unsigned char*)buffer+i;
        pointer[0]=pointer[1];
        pointer[1]=pointer[2];
        pointer[2]=pointer[3];
        pointer[3]=pointer[0];
   }
}
}
Title::Title(const QString& filename){
    int argc=0;
    char* argv[1];
    argv[0]="xxx";
    //app=new QApplication(argc,argv);
    app=new QApplication(argc,argv);
    QGraphicsPolygonItem i;
    m_scene=new QGraphicsScene(10,10,100,100);
    loadDocument(filename,&i,&i);
    m_scene->addText("hello");
    m_scene->setSceneRect(0,0,1000,1000);
    //view=new QGraphicsView(scene);
    //view->show();
    qDebug() << filename;
}
void Title::drawKdenliveTitle(void * buffer ,int width,int height,double position){
    QImage img((uchar*)buffer,width,height,width*4,QImage::Format_ARGB32);
    img.fill(255);
    //qDebug() << "ja" << width << height << buffer << position << endl;
    QList<QGraphicsItem*> items=m_scene->items();
    for(int i=0;i<items.size();i++){
        items[i]->moveBy(width*position,width*position);
    }
    /*
    QPainter p;
    p.begin(&img);
    p.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing);
    p.setFont(QFont("Arial",60));
    p.setPen(QPen(QColor(255,255,255)));
    p.drawText(width*.2+width*20*position,height/2,"test");
    p.end();
*/
    QPainter p1;
    p1.begin(&img);
    m_scene->render(&p1);
    p1.end();
}
int Title::loadDocument(const QString& url, QGraphicsPolygonItem* startv, QGraphicsPolygonItem* endv)
{
    QDomDocument doc;
    if (!m_scene)
        return -1;

        QFile file(url);
        if (file.open(QIODevice::ReadOnly)) {
            qDebug() << "loaded";
            doc.setContent(&file, false);
            file.close();
        }
        return loadFromXml(doc, startv, endv);
}
int Title::loadFromXml(QDomDocument doc, QGraphicsPolygonItem* /*startv*/, QGraphicsPolygonItem* /*endv*/)
{
    QDomNodeList titles = doc.elementsByTagName("kdenlivetitle");
    int maxZValue = 0;
    if (titles.size()) {

        QDomNodeList items = titles.item(0).childNodes();
        for (int i = 0; i < items.count(); i++) {
            QGraphicsItem *gitem = NULL;
            int zValue = items.item(i).attributes().namedItem("z-index").nodeValue().toInt();
            if (zValue > -1000) {
                if (items.item(i).attributes().namedItem("type").nodeValue() == "QGraphicsTextItem") {
                    QDomNamedNodeMap txtProperties = items.item(i).namedItem("content").attributes();
                    QFont font(txtProperties.namedItem("font").nodeValue());
                    font.setBold(txtProperties.namedItem("font-bold").nodeValue().toInt());
                    font.setItalic(txtProperties.namedItem("font-italic").nodeValue().toInt());
                    font.setUnderline(txtProperties.namedItem("font-underline").nodeValue().toInt());
                    // Older Kdenlive version did not store pixel size but point size
                    if (txtProperties.namedItem("font-pixel-size").isNull()) {
                        QFont f2;
                        f2.setPointSize(txtProperties.namedItem("font-size").nodeValue().toInt());
                        font.setPixelSize(QFontInfo(f2).pixelSize());
                    } else
                        font.setPixelSize(txtProperties.namedItem("font-pixel-size").nodeValue().toInt());
                    QColor col(stringToColor(txtProperties.namedItem("font-color").nodeValue()));
                    QGraphicsTextItem *txt = m_scene->addText(items.item(i).namedItem("content").firstChild().nodeValue(), font);
                    txt->setDefaultTextColor(col);
                    txt->setTextInteractionFlags(Qt::NoTextInteraction);
                    if (txtProperties.namedItem("alignment").isNull() == false) {
                        txt->setTextWidth(txt->boundingRect().width());
                        QTextCursor cur = txt->textCursor();
                        QTextBlockFormat format = cur.blockFormat();
                        format.setAlignment((Qt::Alignment) txtProperties.namedItem("alignment").nodeValue().toInt());
                        cur.select(QTextCursor::Document);
                        cur.setBlockFormat(format);
                        txt->setTextCursor(cur);
                        cur.clearSelection();
                        txt->setTextCursor(cur);
                    }

                    if (!txtProperties.namedItem("kdenlive-axis-x-inverted").isNull()) {
                        //txt->setData(OriginXLeft, txtProperties.namedItem("kdenlive-axis-x-inverted").nodeValue().toInt());
                    }
                    if (!txtProperties.namedItem("kdenlive-axis-y-inverted").isNull()) {
                        //txt->setData(OriginYTop, txtProperties.namedItem("kdenlive-axis-y-inverted").nodeValue().toInt());
                    }

                    gitem = txt;
                } else if (items.item(i).attributes().namedItem("type").nodeValue() == "QGraphicsRectItem") {
                    qDebug()  << "rectitem";
                    QString rect = items.item(i).namedItem("content").attributes().namedItem("rect").nodeValue();
                    QString br_str = items.item(i).namedItem("content").attributes().namedItem("brushcolor").nodeValue();
                    QString pen_str = items.item(i).namedItem("content").attributes().namedItem("pencolor").nodeValue();
                    double penwidth = items.item(i).namedItem("content").attributes().namedItem("penwidth").nodeValue().toDouble();
                    QGraphicsRectItem *rec = m_scene->addRect(stringToRect(rect), QPen(QBrush(stringToColor(pen_str)), penwidth), QBrush(stringToColor(br_str)));
                    gitem = rec;
                } else if (items.item(i).attributes().namedItem("type").nodeValue() == "QGraphicsPixmapItem") {
                    QString url = items.item(i).namedItem("content").attributes().namedItem("url").nodeValue();
                    QPixmap pix(url);
                    QGraphicsPixmapItem *rec = m_scene->addPixmap(pix);
                    rec->setData(Qt::UserRole, url);
                    gitem = rec;
                } else if (items.item(i).attributes().namedItem("type").nodeValue() == "QGraphicsSvgItem") {
                    QString url = items.item(i).namedItem("content").attributes().namedItem("url").nodeValue();
                    //QGraphicsSvgItem *rec = new QGraphicsSvgItem(url);
                    //m_scene->addItem(rec);
                    //rec->setData(Qt::UserRole, url);
                    //gitem = rec;
                }
            }
            //pos and transform
            if (gitem) {
                QPointF p(items.item(i).namedItem("position").attributes().namedItem("x").nodeValue().toDouble(),
                          items.item(i).namedItem("position").attributes().namedItem("y").nodeValue().toDouble());
                gitem->setPos(p);
                gitem->setTransform(stringToTransform(items.item(i).namedItem("position").firstChild().firstChild().nodeValue()));
                int zValue = items.item(i).attributes().namedItem("z-index").nodeValue().toInt();
                if (zValue > maxZValue) maxZValue = zValue;
                gitem->setZValue(zValue);
                gitem->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
            }
            if (items.item(i).nodeName() == "background") {
                QColor color = QColor(stringToColor(items.item(i).attributes().namedItem("color").nodeValue()));
                //color.setAlpha(items.item(i).attributes().namedItem("alpha").nodeValue().toInt());
                QList<QGraphicsItem *> items = m_scene->items();
                for (int i = 0; i < items.size(); i++) {
                    if (items.at(i)->zValue() == -1100) {
                        ((QGraphicsRectItem *)items.at(i))->setBrush(QBrush(color));
                        break;
                    }
                }
            } /*else if (items.item(i).nodeName() == "startviewport" && startv) {
                    QPointF p(items.item(i).attributes().namedItem("x").nodeValue().toDouble(), items.item(i).attributes().namedItem("y").nodeValue().toDouble());
                    double width = items.item(i).attributes().namedItem("size").nodeValue().toDouble();
                    QRectF rect(-width, -width / aspect_ratio, width*2.0, width / aspect_ratio*2.0);
                    kDebug() << width << rect;
                    startv->setPolygon(rect);
                    startv->setPos(p);
                } else if (items.item(i).nodeName() == "endviewport" && endv) {
                    QPointF p(items.item(i).attributes().namedItem("x").nodeValue().toDouble(), items.item(i).attributes().namedItem("y").nodeValue().toDouble());
                    double width = items.item(i).attributes().namedItem("size").nodeValue().toDouble();
                    QRectF rect(-width, -width / aspect_ratio, width*2.0, width / aspect_ratio*2.0);
                    kDebug() << width << rect;
                    endv->setPolygon(rect);
                    endv->setPos(p);
                }*/
        }
    }
    return maxZValue;
}

QString Title::colorToString(const QColor& c)
{
    QString ret = "%1,%2,%3,%4";
    ret = ret.arg(c.red()).arg(c.green()).arg(c.blue()).arg(c.alpha());
    return ret;
}

QString Title::rectFToString(const QRectF& c)
{
    QString ret = "%1,%2,%3,%4";
    ret = ret.arg(c.top()).arg(c.left()).arg(c.width()).arg(c.height());
    return ret;
}

QRectF Title::stringToRect(const QString & s)
{

    QStringList l = s.split(',');
    if (l.size() < 4)
        return QRectF();
    return QRectF(l.at(0).toDouble(), l.at(1).toDouble(), l.at(2).toDouble(), l.at(3).toDouble()).normalized();
}

QColor Title::stringToColor(const QString & s)
{
    QStringList l = s.split(',');
    if (l.size() < 4)
        return QColor();
    return QColor(l.at(0).toInt(), l.at(1).toInt(), l.at(2).toInt(), l.at(3).toInt());;
}
QTransform Title::stringToTransform(const QString& s)
{
    QStringList l = s.split(',');
    if (l.size() < 9)
        return QTransform();
    return QTransform(
               l.at(0).toDouble(), l.at(1).toDouble(), l.at(2).toDouble(),
               l.at(3).toDouble(), l.at(4).toDouble(), l.at(5).toDouble(),
               l.at(6).toDouble(), l.at(7).toDouble(), l.at(8).toDouble()
           );
}
<commit_msg>kdenlivetitle_wrapper: fixed typo, not seen in Mac OS (QtXml also needed<commit_after>/*
 * kdenlivetitle_wrapper.cpp -- kdenlivetitle wrapper
 * Copyright (c) 2009 Marco Gittler <g.marco@freenet.de>
 *
 * 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 Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <QtGui/QImage>
#include <QtGui/QPainter>
#include <QtCore/QCoreApplication>
#include <QtGui/QApplication>
#include <QtCore/QDebug>
#include <QtCore/QFile>
#include <QtGui/QGraphicsView>
#include <QtGui/QGraphicsScene>
#include <QtGui/QGraphicsTextItem>
#include <QtGui/QTextCursor>
#include "kdenlivetitle_wrapper.h"
#include <framework/mlt_producer.h>
extern "C" {
void init_qt (const char* c){
    titleclass=new Title(QString(c));
}
void refresh_kdenlivetitle( void* buffer, int width, int height , double position){
   titleclass->drawKdenliveTitle(buffer,width,height,position);
   int i=0;
   unsigned char* pointer;
   //rotate bytes for correct order in mlt
   for (i=0;i<width*height*4;i+=4){
        pointer=(unsigned char*)buffer+i;
        pointer[0]=pointer[1];
        pointer[1]=pointer[2];
        pointer[2]=pointer[3];
        pointer[3]=pointer[0];
   }
}
}
Title::Title(const QString& filename){
    int argc=0;
    char* argv[1];
    argv[0]="xxx";
    //app=new QApplication(argc,argv);
    app=new QApplication(argc,argv);
    QGraphicsPolygonItem i;
    m_scene=new QGraphicsScene(10,10,100,100);
    loadDocument(filename,&i,&i);
    m_scene->addText("hello");
    m_scene->setSceneRect(0,0,1000,1000);
    //view=new QGraphicsView(scene);
    //view->show();
    qDebug() << filename;
}
void Title::drawKdenliveTitle(void * buffer ,int width,int height,double position){
    QImage img((uchar*)buffer,width,height,width*4,QImage::Format_ARGB32);
    img.fill(255);
    //qDebug() << "ja" << width << height << buffer << position << endl;
    QList<QGraphicsItem*> items=m_scene->items();
    for(int i=0;i<items.size();i++){
        items[i]->moveBy(width*position,width*position);
    }
    /*
    QPainter p;
    p.begin(&img);
    p.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing);
    p.setFont(QFont("Arial",60));
    p.setPen(QPen(QColor(255,255,255)));
    p.drawText(width*.2+width*20*position,height/2,"test");
    p.end();
*/
    QPainter p1;
    p1.begin(&img);
    m_scene->render(&p1);
    p1.end();
}
int Title::loadDocument(const QString& url, QGraphicsPolygonItem* startv, QGraphicsPolygonItem* endv)
{
    QDomDocument doc;
    if (!m_scene)
        return -1;

        QFile file(url);
        if (file.open(QIODevice::ReadOnly)) {
            qDebug() << "loaded";
            doc.setContent(&file, false);
            file.close();
        }
        return loadFromXml(doc, startv, endv);
}
int Title::loadFromXml(QDomDocument doc, QGraphicsPolygonItem* /*startv*/, QGraphicsPolygonItem* /*endv*/)
{
    QDomNodeList titles = doc.elementsByTagName("kdenlivetitle");
    int maxZValue = 0;
    if (titles.size()) {

        QDomNodeList items = titles.item(0).childNodes();
        for (int i = 0; i < items.count(); i++) {
            QGraphicsItem *gitem = NULL;
            int zValue = items.item(i).attributes().namedItem("z-index").nodeValue().toInt();
            if (zValue > -1000) {
                if (items.item(i).attributes().namedItem("type").nodeValue() == "QGraphicsTextItem") {
                    QDomNamedNodeMap txtProperties = items.item(i).namedItem("content").attributes();
                    QFont font(txtProperties.namedItem("font").nodeValue());
                    font.setBold(txtProperties.namedItem("font-bold").nodeValue().toInt());
                    font.setItalic(txtProperties.namedItem("font-italic").nodeValue().toInt());
                    font.setUnderline(txtProperties.namedItem("font-underline").nodeValue().toInt());
                    // Older Kdenlive version did not store pixel size but point size
                    if (txtProperties.namedItem("font-pixel-size").isNull()) {
                        QFont f2;
                        f2.setPointSize(txtProperties.namedItem("font-size").nodeValue().toInt());
                        font.setPixelSize(QFontInfo(f2).pixelSize());
                    } else
                        font.setPixelSize(txtProperties.namedItem("font-pixel-size").nodeValue().toInt());
                    QColor col(stringToColor(txtProperties.namedItem("font-color").nodeValue()));
                    QGraphicsTextItem *txt = m_scene->addText(items.item(i).namedItem("content").firstChild().nodeValue(), font);
                    txt->setDefaultTextColor(col);
                    txt->setTextInteractionFlags(Qt::NoTextInteraction);
                    if (txtProperties.namedItem("alignment").isNull() == false) {
                        txt->setTextWidth(txt->boundingRect().width());
                        QTextCursor cur = txt->textCursor();
                        QTextBlockFormat format = cur.blockFormat();
                        format.setAlignment((Qt::Alignment) txtProperties.namedItem("alignment").nodeValue().toInt());
                        cur.select(QTextCursor::Document);
                        cur.setBlockFormat(format);
                        txt->setTextCursor(cur);
                        cur.clearSelection();
                        txt->setTextCursor(cur);
                    }

                    if (!txtProperties.namedItem("kdenlive-axis-x-inverted").isNull()) {
                        //txt->setData(OriginXLeft, txtProperties.namedItem("kdenlive-axis-x-inverted").nodeValue().toInt());
                    }
                    if (!txtProperties.namedItem("kdenlive-axis-y-inverted").isNull()) {
                        //txt->setData(OriginYTop, txtProperties.namedItem("kdenlive-axis-y-inverted").nodeValue().toInt());
                    }

                    gitem = txt;
                } else if (items.item(i).attributes().namedItem("type").nodeValue() == "QGraphicsRectItem") {
                    qDebug()  << "rectitem";
                    QString rect = items.item(i).namedItem("content").attributes().namedItem("rect").nodeValue();
                    QString br_str = items.item(i).namedItem("content").attributes().namedItem("brushcolor").nodeValue();
                    QString pen_str = items.item(i).namedItem("content").attributes().namedItem("pencolor").nodeValue();
                    double penwidth = items.item(i).namedItem("content").attributes().namedItem("penwidth").nodeValue().toDouble();
                    QGraphicsRectItem *rec = m_scene->addRect(stringToRect(rect), QPen(QBrush(stringToColor(pen_str)), penwidth), QBrush(stringToColor(br_str)));
                    gitem = rec;
                } else if (items.item(i).attributes().namedItem("type").nodeValue() == "QGraphicsPixmapItem") {
                    QString url = items.item(i).namedItem("content").attributes().namedItem("url").nodeValue();
                    QPixmap pix(url);
                    QGraphicsPixmapItem *rec = m_scene->addPixmap(pix);
                    rec->setData(Qt::UserRole, url);
                    gitem = rec;
                } else if (items.item(i).attributes().namedItem("type").nodeValue() == "QGraphicsSvgItem") {
                    QString url = items.item(i).namedItem("content").attributes().namedItem("url").nodeValue();
                    //QGraphicsSvgItem *rec = new QGraphicsSvgItem(url);
                    //m_scene->addItem(rec);
                    //rec->setData(Qt::UserRole, url);
                    //gitem = rec;
                }
            }
            //pos and transform
            if (gitem) {
                QPointF p(items.item(i).namedItem("position").attributes().namedItem("x").nodeValue().toDouble(),
                          items.item(i).namedItem("position").attributes().namedItem("y").nodeValue().toDouble());
                gitem->setPos(p);
                gitem->setTransform(stringToTransform(items.item(i).namedItem("position").firstChild().firstChild().nodeValue()));
                int zValue = items.item(i).attributes().namedItem("z-index").nodeValue().toInt();
                if (zValue > maxZValue) maxZValue = zValue;
                gitem->setZValue(zValue);
                gitem->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
            }
            if (items.item(i).nodeName() == "background") {
                QColor color = QColor(stringToColor(items.item(i).attributes().namedItem("color").nodeValue()));
                //color.setAlpha(items.item(i).attributes().namedItem("alpha").nodeValue().toInt());
                QList<QGraphicsItem *> items = m_scene->items();
                for (int i = 0; i < items.size(); i++) {
                    if (items.at(i)->zValue() == -1100) {
                        ((QGraphicsRectItem *)items.at(i))->setBrush(QBrush(color));
                        break;
                    }
                }
            } /*else if (items.item(i).nodeName() == "startviewport" && startv) {
                    QPointF p(items.item(i).attributes().namedItem("x").nodeValue().toDouble(), items.item(i).attributes().namedItem("y").nodeValue().toDouble());
                    double width = items.item(i).attributes().namedItem("size").nodeValue().toDouble();
                    QRectF rect(-width, -width / aspect_ratio, width*2.0, width / aspect_ratio*2.0);
                    kDebug() << width << rect;
                    startv->setPolygon(rect);
                    startv->setPos(p);
                } else if (items.item(i).nodeName() == "endviewport" && endv) {
                    QPointF p(items.item(i).attributes().namedItem("x").nodeValue().toDouble(), items.item(i).attributes().namedItem("y").nodeValue().toDouble());
                    double width = items.item(i).attributes().namedItem("size").nodeValue().toDouble();
                    QRectF rect(-width, -width / aspect_ratio, width*2.0, width / aspect_ratio*2.0);
                    kDebug() << width << rect;
                    endv->setPolygon(rect);
                    endv->setPos(p);
                }*/
        }
    }
    return maxZValue;
}

QString Title::colorToString(const QColor& c)
{
    QString ret = "%1,%2,%3,%4";
    ret = ret.arg(c.red()).arg(c.green()).arg(c.blue()).arg(c.alpha());
    return ret;
}

QString Title::rectFToString(const QRectF& c)
{
    QString ret = "%1,%2,%3,%4";
    ret = ret.arg(c.top()).arg(c.left()).arg(c.width()).arg(c.height());
    return ret;
}

QRectF Title::stringToRect(const QString & s)
{

    QStringList l = s.split(',');
    if (l.size() < 4)
        return QRectF();
    return QRectF(l.at(0).toDouble(), l.at(1).toDouble(), l.at(2).toDouble(), l.at(3).toDouble()).normalized();
}

QColor Title::stringToColor(const QString & s)
{
    QStringList l = s.split(',');
    if (l.size() < 4)
        return QColor();
    return QColor(l.at(0).toInt(), l.at(1).toInt(), l.at(2).toInt(), l.at(3).toInt());;
}
QTransform Title::stringToTransform(const QString& s)
{
    QStringList l = s.split(',');
    if (l.size() < 9)
        return QTransform();
    return QTransform(
               l.at(0).toDouble(), l.at(1).toDouble(), l.at(2).toDouble(),
               l.at(3).toDouble(), l.at(4).toDouble(), l.at(5).toDouble(),
               l.at(6).toDouble(), l.at(7).toDouble(), l.at(8).toDouble()
           );
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 2010  George Kiagiadakis <kiagiadakis.george@gmail.com>

    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 program 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 program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "element.h"
#include "pad.h"
#include "query.h"
#include "clock.h"
#include "event.h"
#include <gst/gstelement.h>
#include <gst/gstutils.h>

namespace QGst {

State Element::currentState() const
{
    State r;
    getState(&r, NULL, 0);
    return r;
}

State Element::pendingState() const
{
    State r;
    getState(NULL, &r, 0);
    return r;
}

StateChangeReturn Element::getState(State *state, State *pending, ClockTime timeout) const
{
    GstState curState, pendingState;
    GstStateChangeReturn result = gst_element_get_state(object<GstElement>(),
                                                        &curState, &pendingState, timeout);
    if (state) {
        *state = static_cast<State>(curState);
    }
    if (pending) {
        *pending = static_cast<State>(pendingState);
    }
    return static_cast<StateChangeReturn>(result);
}

StateChangeReturn Element::setState(State state)
{
    return static_cast<StateChangeReturn>(gst_element_set_state(object<GstElement>(),
                                                                static_cast<GstState>(state)));
}

bool Element::syncStateWithParent()
{
   return gst_element_sync_state_with_parent(object<GstElement>());
}

bool Element::stateIsLocked() const
{
    return gst_element_is_locked_state(object<GstElement>());
}

bool Element::setStateLocked(bool locked)
{
    return gst_element_set_locked_state(object<GstElement>(), locked);
}

bool Element::addPad(const PadPtr & pad)
{
    return gst_element_add_pad(object<GstElement>(), pad);
}

bool Element::removePad(const PadPtr & pad)
{
    return gst_element_remove_pad(object<GstElement>(), pad);
}

PadPtr Element::getStaticPad(const char *name)
{
    GstPad *pad = gst_element_get_static_pad(object<GstElement>(), name);
    return PadPtr::wrap(pad, false);
}

PadPtr Element::getRequestPad(const char *name)
{
    GstPad *pad = gst_element_get_request_pad(object<GstElement>(), name);
    return PadPtr::wrap(pad, false);
}

void Element::releaseRequestPad(const PadPtr & pad)
{
    gst_element_release_request_pad(object<GstElement>(), pad);
}

bool Element::link(const char *srcPadName, const ElementPtr & dest,
                   const char *sinkPadName, const CapsPtr & filter)
{
    return gst_element_link_pads_filtered(object<GstElement>(), srcPadName,
                                          dest, sinkPadName, filter);
}

bool Element::link(const char *srcPadName, const ElementPtr & dest, const CapsPtr & filter)
{
    return link(srcPadName, dest, NULL, filter);
}

bool Element::link(const ElementPtr & dest, const char *sinkPadName, const CapsPtr & filter)
{
    return link(NULL, dest, sinkPadName, filter);
}

bool Element::link(const ElementPtr & dest, const CapsPtr & filter)
{
    return link(NULL, dest, NULL, filter);
}

void Element::unlink(const char *srcPadName, const ElementPtr & dest, const char *sinkPadName)
{
    //FIXME-0.11 This is not entirely correct. Unfortunately I didn't notice
    //that gst_element_unlink_pads requires both pad names when I wrote this
    //function, and it cannot be changed now. For the moment, if the sink
    //pad name is not given, we will assume it is "sink".
    if (!sinkPadName) {
        sinkPadName = "sink";
    }

    gst_element_unlink_pads(object<GstElement>(), srcPadName, dest, sinkPadName);
}

void Element::unlink(const ElementPtr & dest, const char *sinkPadName)
{
    if (sinkPadName) {
        //FIXME-0.11 This is not entirely correct. Unfortunately I didn't notice
        //that gst_element_unlink_pads requires both pad names when I wrote this
        //function, and it cannot be changed now. For the moment, if the source
        //pad name is not given, we will assume it is "src".
        unlink("src", dest, sinkPadName);
    } else {
        gst_element_unlink(object<GstElement>(), dest);
    }
}

bool Element::query(const QueryPtr & query)
{
    return gst_element_query(object<GstElement>(), query);
}

ClockPtr Element::clock() const
{
    if (gst_element_provides_clock(object<GstElement>())) {
        return ClockPtr::wrap(gst_element_get_clock(object<GstElement>()), false);
    } else {
        return ClockPtr();
    }
}

bool Element::setClock(const ClockPtr & clock)
{
    return gst_element_set_clock(object<GstElement>(), clock);
}

bool Element::sendEvent(const EventPtr &event)
{
    //Sending an event passes ownership of it, so we need to strong ref() it as we still
    //hold a pointer to the object, and will release it when the wrapper is cleared.
    gst_event_ref(event);
    return gst_element_send_event(object<GstElement>(), event);
}

bool Element::seek(Format format, SeekFlags flags, quint64 position)
{
    return gst_element_seek_simple(object<GstElement>(), static_cast<GstFormat>(format),
                                   static_cast<GstSeekFlags>(static_cast<int>(flags)), position);
}

}
<commit_msg>src/QGst/element.cpp gst_element_provides_clock was removed<commit_after>/*
    Copyright (C) 2010  George Kiagiadakis <kiagiadakis.george@gmail.com>

    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 program 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 program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "element.h"
#include "pad.h"
#include "query.h"
#include "clock.h"
#include "event.h"
#include <gst/gstelement.h>
#include <gst/gstutils.h>

namespace QGst {

State Element::currentState() const
{
    State r;
    getState(&r, NULL, 0);
    return r;
}

State Element::pendingState() const
{
    State r;
    getState(NULL, &r, 0);
    return r;
}

StateChangeReturn Element::getState(State *state, State *pending, ClockTime timeout) const
{
    GstState curState, pendingState;
    GstStateChangeReturn result = gst_element_get_state(object<GstElement>(),
                                                        &curState, &pendingState, timeout);
    if (state) {
        *state = static_cast<State>(curState);
    }
    if (pending) {
        *pending = static_cast<State>(pendingState);
    }
    return static_cast<StateChangeReturn>(result);
}

StateChangeReturn Element::setState(State state)
{
    return static_cast<StateChangeReturn>(gst_element_set_state(object<GstElement>(),
                                                                static_cast<GstState>(state)));
}

bool Element::syncStateWithParent()
{
   return gst_element_sync_state_with_parent(object<GstElement>());
}

bool Element::stateIsLocked() const
{
    return gst_element_is_locked_state(object<GstElement>());
}

bool Element::setStateLocked(bool locked)
{
    return gst_element_set_locked_state(object<GstElement>(), locked);
}

bool Element::addPad(const PadPtr & pad)
{
    return gst_element_add_pad(object<GstElement>(), pad);
}

bool Element::removePad(const PadPtr & pad)
{
    return gst_element_remove_pad(object<GstElement>(), pad);
}

PadPtr Element::getStaticPad(const char *name)
{
    GstPad *pad = gst_element_get_static_pad(object<GstElement>(), name);
    return PadPtr::wrap(pad, false);
}

PadPtr Element::getRequestPad(const char *name)
{
    GstPad *pad = gst_element_get_request_pad(object<GstElement>(), name);
    return PadPtr::wrap(pad, false);
}

void Element::releaseRequestPad(const PadPtr & pad)
{
    gst_element_release_request_pad(object<GstElement>(), pad);
}

bool Element::link(const char *srcPadName, const ElementPtr & dest,
                   const char *sinkPadName, const CapsPtr & filter)
{
    return gst_element_link_pads_filtered(object<GstElement>(), srcPadName,
                                          dest, sinkPadName, filter);
}

bool Element::link(const char *srcPadName, const ElementPtr & dest, const CapsPtr & filter)
{
    return link(srcPadName, dest, NULL, filter);
}

bool Element::link(const ElementPtr & dest, const char *sinkPadName, const CapsPtr & filter)
{
    return link(NULL, dest, sinkPadName, filter);
}

bool Element::link(const ElementPtr & dest, const CapsPtr & filter)
{
    return link(NULL, dest, NULL, filter);
}

void Element::unlink(const char *srcPadName, const ElementPtr & dest, const char *sinkPadName)
{
    //FIXME-0.11 This is not entirely correct. Unfortunately I didn't notice
    //that gst_element_unlink_pads requires both pad names when I wrote this
    //function, and it cannot be changed now. For the moment, if the sink
    //pad name is not given, we will assume it is "sink".
    if (!sinkPadName) {
        sinkPadName = "sink";
    }

    gst_element_unlink_pads(object<GstElement>(), srcPadName, dest, sinkPadName);
}

void Element::unlink(const ElementPtr & dest, const char *sinkPadName)
{
    if (sinkPadName) {
        //FIXME-0.11 This is not entirely correct. Unfortunately I didn't notice
        //that gst_element_unlink_pads requires both pad names when I wrote this
        //function, and it cannot be changed now. For the moment, if the source
        //pad name is not given, we will assume it is "src".
        unlink("src", dest, sinkPadName);
    } else {
        gst_element_unlink(object<GstElement>(), dest);
    }
}

bool Element::query(const QueryPtr & query)
{
    return gst_element_query(object<GstElement>(), query);
}

ClockPtr Element::clock() const
{
    return ClockPtr::wrap(gst_element_get_clock(object<GstElement>()), false);
}

bool Element::setClock(const ClockPtr & clock)
{
    return gst_element_set_clock(object<GstElement>(), clock);
}

bool Element::sendEvent(const EventPtr &event)
{
    //Sending an event passes ownership of it, so we need to strong ref() it as we still
    //hold a pointer to the object, and will release it when the wrapper is cleared.
    gst_event_ref(event);
    return gst_element_send_event(object<GstElement>(), event);
}

bool Element::seek(Format format, SeekFlags flags, quint64 position)
{
    return gst_element_seek_simple(object<GstElement>(), static_cast<GstFormat>(format),
                                   static_cast<GstSeekFlags>(static_cast<int>(flags)), position);
}

}
<|endoftext|>