<commit_before>#include "precompiled.hpp"
#include "model/OpenGLState.hpp"

namespace balls {

OpenGLState::OpenGLState(OpenGLPointers& pointers, QObject* parent)
  : QObject(parent), m_gl(pointers) {
  Q_ASSUME(m_gl.gl30 != nullptr);
}

bool OpenGLState::hasGl31() const noexcept {
  return m_gl.gl31 != nullptr;
}

bool OpenGLState::hasGl32() const noexcept {
  return m_gl.gl32 != nullptr;
}

bool OpenGLState::hasGl33() const noexcept {
  return m_gl.gl33 != nullptr;
}

bool OpenGLState::hasGl40() const noexcept {
  return m_gl.gl40 != nullptr;
}

bool OpenGLState::hasGl41() const noexcept {
  return m_gl.gl41 != nullptr;
}

bool OpenGLState::hasGl42() const noexcept {
  return m_gl.gl42 != nullptr;
}

bool OpenGLState::hasGl43() const noexcept {
  return m_gl.gl43 != nullptr;
}

bool OpenGLState::hasGl44() const noexcept {
  return false;
  // TODO: Upgrade Qt version
}

bool OpenGLState::hasGl45() const noexcept {
  return false;
  // TODO: Upgrade Qt version
}

void OpenGLState::setGlFeature(bool enabled, GLenum feature) {
  if (enabled) {
    m_gl.gl30Current()->glEnable(feature);
  } else {
    m_gl.gl30Current()->glDisable(feature);
  }
}
}
<commit_msg>No more incomplete types<commit_after>#include "precompiled.hpp"
#include "model/OpenGLState.hpp"

#include <QOpenGLFunctions_3_0>

namespace balls {

OpenGLState::OpenGLState(OpenGLPointers& pointers, QObject* parent)
  : QObject(parent), m_gl(pointers) {
  Q_ASSUME(m_gl.gl30 != nullptr);
}

bool OpenGLState::hasGl31() const noexcept {
  return m_gl.gl31 != nullptr;
}

bool OpenGLState::hasGl32() const noexcept {
  return m_gl.gl32 != nullptr;
}

bool OpenGLState::hasGl33() const noexcept {
  return m_gl.gl33 != nullptr;
}

bool OpenGLState::hasGl40() const noexcept {
  return m_gl.gl40 != nullptr;
}

bool OpenGLState::hasGl41() const noexcept {
  return m_gl.gl41 != nullptr;
}

bool OpenGLState::hasGl42() const noexcept {
  return m_gl.gl42 != nullptr;
}

bool OpenGLState::hasGl43() const noexcept {
  return m_gl.gl43 != nullptr;
}

bool OpenGLState::hasGl44() const noexcept {
  return false;
  // TODO: Upgrade Qt version
}

bool OpenGLState::hasGl45() const noexcept {
  return false;
  // TODO: Upgrade Qt version
}

void OpenGLState::setGlFeature(bool enabled, GLenum feature) {
  if (enabled) {
    m_gl.gl30Current()->glEnable(feature);
  } else {
    m_gl.gl30Current()->glDisable(feature);
  }
}
}
<|endoftext|>


<commit_before>#include "Rendering/GBuffer.h"
#include "Rendering/RenderTargetDX11.h"
#include "Rendering/DepthStencilBufferDX11.h"
#include "Rendering/BlendState.h"

constexpr size_t GBUFFER_RENDER_TARGET_NUM = 5;

namespace Mile
{
   GBuffer::GBuffer(RendererDX11* renderer) :
      m_renderer(renderer),
      m_depthStencilBuffer(nullptr),
      m_positionBuffer(nullptr),
      m_albedoBuffer(nullptr),
      m_emissiveAOBuffer(nullptr),
      m_normalBuffer(nullptr),
      m_metallicRoughnessBuffer(nullptr),
      m_blendState(nullptr)
   {
   }

   GBuffer::~GBuffer()
   {
      SafeDelete(m_positionBuffer);
      SafeDelete(m_albedoBuffer);
      SafeDelete(m_emissiveAOBuffer);
      SafeDelete(m_normalBuffer);
      SafeDelete(m_metallicRoughnessBuffer);
      SafeDelete(m_blendState);
   }

   bool GBuffer::Init(unsigned int width, unsigned int height)
   {
      bool bIsInitialized = m_normalBuffer != nullptr || m_positionBuffer != nullptr;
      if (m_renderer == nullptr || bIsInitialized)
      {
         return false;
      }

      m_positionBuffer = new RenderTargetDX11(m_renderer);
      m_albedoBuffer = new RenderTargetDX11(m_renderer);
      m_emissiveAOBuffer = new RenderTargetDX11(m_renderer);
      m_normalBuffer = new RenderTargetDX11(m_renderer);
      m_metallicRoughnessBuffer = new RenderTargetDX11(m_renderer);
      m_blendState = new BlendState(m_renderer);

      if (!m_positionBuffer->Init(width, height, DXGI_FORMAT_R32G32B32A32_FLOAT))
      {
         return false;
      }

      if (!m_albedoBuffer->Init(width, height, DXGI_FORMAT_R32G32B32A32_FLOAT))
      {
         return false;
      }

      if (!m_emissiveAOBuffer->Init(width, height, DXGI_FORMAT_R32G32B32A32_FLOAT))
      {
         return false;
      }

      if (!m_normalBuffer->Init(width, height, DXGI_FORMAT_R32G32B32A32_FLOAT))
      {
         return false;
      }

      if (!m_metallicRoughnessBuffer->Init(width, height, DXGI_FORMAT_R32G32B32A32_FLOAT))
      {
         return false;
      }

      if (!m_blendState->Init())
      {
         return false;
      }

      return true;
   }

   bool GBuffer::BindAsRenderTarget(ID3D11DeviceContext& deviceContext)
   {
      bool bIsInitialized = m_normalBuffer != nullptr && m_positionBuffer != nullptr;
      if (m_renderer == nullptr || !bIsInitialized)
      {
         return false;
      }

      ID3D11DepthStencilView* dsv = nullptr;
      if (m_depthStencilBuffer != nullptr)
      {
         dsv = m_depthStencilBuffer->GetDSV();
         deviceContext.ClearDepthStencilView(dsv,
            D3D11_CLEAR_DEPTH,
            1.0f,
            0);
      }

      std::array<ID3D11RenderTargetView*, GBUFFER_RENDER_TARGET_NUM> targets{
         m_positionBuffer->GetRTV(),
         m_albedoBuffer->GetRTV(),
         m_emissiveAOBuffer->GetRTV(),
         m_normalBuffer->GetRTV(),
         m_metallicRoughnessBuffer->GetRTV()
      };

      const float clearColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
      for (auto rtv : targets)
      {
         deviceContext.ClearRenderTargetView(rtv, clearColor);
      }

      deviceContext.OMSetRenderTargets(GBUFFER_RENDER_TARGET_NUM, targets.data(), dsv);

      if (m_blendState != nullptr)
      {
         if (!m_blendState->Bind(deviceContext))
         {
            return false;
         }
      }

      return true;
   }

   bool GBuffer::BindAsShaderResource(ID3D11DeviceContext& deviceContext, unsigned int startSlot)
   {
      bool bIsInitialized = m_normalBuffer != nullptr && m_positionBuffer != nullptr;
      if (m_renderer == nullptr || !bIsInitialized)
      {
         return false;
      }

      std::array<RenderTargetDX11*, GBUFFER_RENDER_TARGET_NUM> targets{
         m_positionBuffer,
         m_albedoBuffer,
         m_emissiveAOBuffer,
         m_normalBuffer,
         m_metallicRoughnessBuffer };

      for (unsigned int idx = 0; idx < targets.size(); ++idx)
      {
         targets[idx]->BindAsShaderResource(deviceContext, startSlot + idx, EShaderType::PixelShader);
      }

      return true;
   }

   void GBuffer::UnbindShaderResource(ID3D11DeviceContext& deviceContext)
   {
      bool bIsInitialized = m_normalBuffer != nullptr && m_positionBuffer != nullptr;
      if (bIsInitialized)
      {
         m_positionBuffer->UnbindShaderResource(deviceContext);
         m_albedoBuffer->UnbindShaderResource(deviceContext);
         m_emissiveAOBuffer->UnbindShaderResource(deviceContext);
         m_normalBuffer->UnbindShaderResource(deviceContext);
         m_metallicRoughnessBuffer->UnbindShaderResource(deviceContext);

         std::array<ID3D11RenderTargetView*, GBUFFER_RENDER_TARGET_NUM> targets{
            nullptr,
            nullptr,
            nullptr,
            nullptr,
            nullptr
         };

         deviceContext.OMSetRenderTargets(GBUFFER_RENDER_TARGET_NUM, targets.data(), nullptr);
      }
   }

   void GBuffer::UnbindRenderTarget(ID3D11DeviceContext& deviceContext)
   {
      bool bIsInitialized = m_normalBuffer != nullptr && m_positionBuffer != nullptr;
      if (bIsInitialized)
      {
         std::array<ID3D11RenderTargetView*, GBUFFER_RENDER_TARGET_NUM> targets{
            nullptr,
            nullptr,
            nullptr,
            nullptr,
            nullptr
         };

         deviceContext.OMSetRenderTargets(GBUFFER_RENDER_TARGET_NUM, targets.data(), nullptr);
      }
   }
}<commit_msg>Modify format of buffer in g-buffer<commit_after>#include "Rendering/GBuffer.h"
#include "Rendering/RenderTargetDX11.h"
#include "Rendering/DepthStencilBufferDX11.h"
#include "Rendering/BlendState.h"

constexpr size_t GBUFFER_RENDER_TARGET_NUM = 5;

namespace Mile
{
   GBuffer::GBuffer(RendererDX11* renderer) :
      m_renderer(renderer),
      m_depthStencilBuffer(nullptr),
      m_positionBuffer(nullptr),
      m_albedoBuffer(nullptr),
      m_emissiveAOBuffer(nullptr),
      m_normalBuffer(nullptr),
      m_metallicRoughnessBuffer(nullptr),
      m_blendState(nullptr)
   {
   }

   GBuffer::~GBuffer()
   {
      SafeDelete(m_positionBuffer);
      SafeDelete(m_albedoBuffer);
      SafeDelete(m_emissiveAOBuffer);
      SafeDelete(m_normalBuffer);
      SafeDelete(m_metallicRoughnessBuffer);
      SafeDelete(m_blendState);
   }

   bool GBuffer::Init(unsigned int width, unsigned int height)
   {
      bool bIsInitialized = m_normalBuffer != nullptr || m_positionBuffer != nullptr;
      if (m_renderer == nullptr || bIsInitialized)
      {
         return false;
      }

      m_positionBuffer = new RenderTargetDX11(m_renderer);
      m_albedoBuffer = new RenderTargetDX11(m_renderer);
      m_emissiveAOBuffer = new RenderTargetDX11(m_renderer);
      m_normalBuffer = new RenderTargetDX11(m_renderer);
      m_metallicRoughnessBuffer = new RenderTargetDX11(m_renderer);
      m_blendState = new BlendState(m_renderer);

      if (!m_positionBuffer->Init(width, height, DXGI_FORMAT_R32G32B32A32_FLOAT))
      {
         return false;
      }

      if (!m_albedoBuffer->Init(width, height, DXGI_FORMAT_R8G8B8A8_UNORM))
      {
         return false;
      }

      if (!m_emissiveAOBuffer->Init(width, height, DXGI_FORMAT_R8G8B8A8_UNORM))
      {
         return false;
      }

      if (!m_normalBuffer->Init(width, height, DXGI_FORMAT_R32G32B32A32_FLOAT))
      {
         return false;
      }

      if (!m_metallicRoughnessBuffer->Init(width, height, DXGI_FORMAT_R8G8B8A8_UNORM))
      {
         return false;
      }

      if (!m_blendState->Init())
      {
         return false;
      }

      return true;
   }

   bool GBuffer::BindAsRenderTarget(ID3D11DeviceContext& deviceContext)
   {
      bool bIsInitialized = m_normalBuffer != nullptr && m_positionBuffer != nullptr;
      if (m_renderer == nullptr || !bIsInitialized)
      {
         return false;
      }

      ID3D11DepthStencilView* dsv = nullptr;
      if (m_depthStencilBuffer != nullptr)
      {
         dsv = m_depthStencilBuffer->GetDSV();
         deviceContext.ClearDepthStencilView(dsv,
            D3D11_CLEAR_DEPTH,
            1.0f,
            0);
      }

      std::array<ID3D11RenderTargetView*, GBUFFER_RENDER_TARGET_NUM> targets{
         m_positionBuffer->GetRTV(),
         m_albedoBuffer->GetRTV(),
         m_emissiveAOBuffer->GetRTV(),
         m_normalBuffer->GetRTV(),
         m_metallicRoughnessBuffer->GetRTV()
      };

      const float clearColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
      for (auto rtv : targets)
      {
         deviceContext.ClearRenderTargetView(rtv, clearColor);
      }

      deviceContext.OMSetRenderTargets(GBUFFER_RENDER_TARGET_NUM, targets.data(), dsv);

      if (m_blendState != nullptr)
      {
         if (!m_blendState->Bind(deviceContext))
         {
            return false;
         }
      }

      return true;
   }

   bool GBuffer::BindAsShaderResource(ID3D11DeviceContext& deviceContext, unsigned int startSlot)
   {
      bool bIsInitialized = m_normalBuffer != nullptr && m_positionBuffer != nullptr;
      if (m_renderer == nullptr || !bIsInitialized)
      {
         return false;
      }

      std::array<RenderTargetDX11*, GBUFFER_RENDER_TARGET_NUM> targets{
         m_positionBuffer,
         m_albedoBuffer,
         m_emissiveAOBuffer,
         m_normalBuffer,
         m_metallicRoughnessBuffer };

      for (unsigned int idx = 0; idx < targets.size(); ++idx)
      {
         targets[idx]->BindAsShaderResource(deviceContext, startSlot + idx, EShaderType::PixelShader);
      }

      return true;
   }

   void GBuffer::UnbindShaderResource(ID3D11DeviceContext& deviceContext)
   {
      bool bIsInitialized = m_normalBuffer != nullptr && m_positionBuffer != nullptr;
      if (bIsInitialized)
      {
         m_positionBuffer->UnbindShaderResource(deviceContext);
         m_albedoBuffer->UnbindShaderResource(deviceContext);
         m_emissiveAOBuffer->UnbindShaderResource(deviceContext);
         m_normalBuffer->UnbindShaderResource(deviceContext);
         m_metallicRoughnessBuffer->UnbindShaderResource(deviceContext);

         std::array<ID3D11RenderTargetView*, GBUFFER_RENDER_TARGET_NUM> targets{
            nullptr,
            nullptr,
            nullptr,
            nullptr,
            nullptr
         };

         deviceContext.OMSetRenderTargets(GBUFFER_RENDER_TARGET_NUM, targets.data(), nullptr);
      }
   }

   void GBuffer::UnbindRenderTarget(ID3D11DeviceContext& deviceContext)
   {
      bool bIsInitialized = m_normalBuffer != nullptr && m_positionBuffer != nullptr;
      if (bIsInitialized)
      {
         std::array<ID3D11RenderTargetView*, GBUFFER_RENDER_TARGET_NUM> targets{
            nullptr,
            nullptr,
            nullptr,
            nullptr,
            nullptr
         };

         deviceContext.OMSetRenderTargets(GBUFFER_RENDER_TARGET_NUM, targets.data(), nullptr);
      }
   }
}<|endoftext|>


<commit_before>#include <opencv2/core.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/dpm.hpp>
#include <opencv2/tracking.hpp>

#include <cstring>
#include <fstream>
#include <iostream>
#include <stdio.h>

using namespace cv;
using namespace cv::dpm;
using namespace std;

void drawDPMBoxes(Mat &frame,
                  vector<DPMDetector::ObjectDetection> ds,
                  Scalar color,
                  string text);

void drawKCFBoxes(Mat &frame,
                  Rect rect,
                  Scalar color,
                  string text);

bool write_count(int count);

static const float LOW_PASS = 0.5;
static const string CLEAR_FILE = "/opt/mz-bicycle-commuter/reset";
static const string LEFT_OUTPUT_FILE = "/opt/mz-bicycle-commuter/left.count";

int main( int argc, char** argv )
{
    bool ENTER_LEAVE = true;
    bool FRAMES_FIRST = true;

    Mat frame;
    Mat image;
    const char* keys =
    {
        "{@model_path    | | Path of the DPM cascade model}"
        "{@video_source    | | Video Source}"
    };

    CommandLineParser parser(argc, argv, keys);
    string model_path(parser.get<string>(0));
    bool show_image (parser.get<bool>(1));

    // init DPM
    Ptr<DPMDetector> detector = \
    DPMDetector::create(vector<string>(1, model_path));
    vector<DPMDetector::ObjectDetection> ds;

    // init KCF
    Ptr<Tracker> tracker;
    Rect2d roi;
    Rect result; // Tracker results
    int count = 0;
    //use web camera
    VideoCapture capture(0);
    capture.set(CV_CAP_PROP_FRAME_WIDTH, 320);
    capture.set(CV_CAP_PROP_FRAME_HEIGHT, 240);
  //  capture.set(CV_CAP_PROP_CONVERT_RGB, false);
	  capture.set(CV_CAP_PROP_FPS, 10);
    double fps = capture.get(CAP_PROP_FPS);

     cout << fps << endl;

    if( model_path.empty() )
    {
        cerr << "Fail to open model file!" << endl;
        return -1;
    }

    if ( !capture.isOpened() )
    {
        cerr << "Fail to open default camera (0)!" << endl;
        return -1;
    }

    // create window
    if (show_image) {
        namedWindow("tracker", 1);
    }
    int frame_count = 10;
    while (true){
        //get the frame
        capture >> frame;

        if ( frame.empty() ){
            cerr << "Fail to get video!" << endl;
            break;
        }

        //DPM detection
        if( ENTER_LEAVE )
        {

            if ((++frame_count % 10) != 0) {
              // cout << "skip" << endl;
              continue;
            }
            // cout << "no skip" << endl;

            frame_count = 0;

            double t = (double) getTickCount(); //start time

            frame.copyTo(image);

            // detection
            detector->detect(image, ds);

            ds.erase(std::remove_if(ds.begin(),
                                    ds.end(),
                                    [&](const DPMDetector::ObjectDetection& o)
                                    {return o.score < LOW_PASS;}
                                    ),
                     ds.end());
            if (!ds.empty())
            {
                for (const auto i: ds)
                    std::cout << i.score << ' ';
                cout << endl;

                ENTER_LEAVE = false;
                FRAMES_FIRST = true;
            }

            t = ((double) getTickCount() - t)/getTickFrequency(); //elapsed time
            string text = format("%0.1f fps", 1.0/t); //calculate fps

            // draw the tracked object
            Scalar color(0,0,255);
            drawDPMBoxes(frame, ds, color, text);
        } else {

            //KCF tracking
            double t = (double) getTickCount(); //start time
            if ( FRAMES_FIRST )
            {
                // get bounding box
                roi = ds[0].rect;

                // initialize the tracker
                tracker = Tracker::create("KCF");
                bool success = tracker->init(frame,roi);

                FRAMES_FIRST = !success ;
            }

            // Update
            else{

                // update the tracking result
                bool was_successful = tracker->update(frame,roi);

                if (!was_successful) {
                    continue;
                }
                result = roi;
                //DPM model detect UAV's leave
                int x_value = 640 - result.x + result.width/2;
                int y_value = 480 - result.y + result.height/2;
                if (!(result.x > 0 && result.y > 0 && x_value > 0 && y_value > 0)){
                    ENTER_LEAVE = true;
                    count++;
                    bool reset_count = write_count(count);
                     string count_text;
                    if (reset_count) {
                        count = 0;
                        count_text = "Count was reset";
                    } else {
                        count_text  = format("%ld bicycles!", count);
                    }

                    cout << count_text << endl;

                }
            }
            t = ((double) getTickCount() - t)/getTickFrequency(); //elapsed time
            string text = format("%0.1f fps", 1.0/t); //calculate fps

            // draw the tracked object
            Scalar color(0,0,255);
            drawKCFBoxes(frame, roi, color, text);
        }

        // show image with the tracked object
        if(show_image) {
            imshow("tracker",frame);
        }
        if(waitKey(1)==27)break;
    }
    return 0;
}

bool write_count(int count)
{
    ofstream resultsFile;
    bool should_clear = std::ifstream(CLEAR_FILE).good();

    int file_count = should_clear ? 1 : count;
    resultsFile.open(LEFT_OUTPUT_FILE);
    resultsFile << file_count  << endl;
    resultsFile.close();
    if(should_clear) {
        remove(CLEAR_FILE.c_str());
    }

    return should_clear;
}

void drawDPMBoxes(Mat &frame,
                  vector<DPMDetector::ObjectDetection> ds,
                  Scalar color,
                  string text)
{
    for (unsigned int i = 0; i < ds.size(); i++)
    {
        rectangle(frame, ds[i].rect, color, 2);
    }

    // draw text on image
    Scalar textColor(255,0,0);
    putText(frame, text, Point(10,50), FONT_HERSHEY_PLAIN, 2, textColor, 2);
}

void drawKCFBoxes(Mat &frame,
                  Rect rect,
                  Scalar color,
                  string text)
{
    rectangle(frame, rect, color, 2);

    // draw text on image
    Scalar textColor(255,0,0);
    putText(frame, text, Point(10,50), FONT_HERSHEY_PLAIN, 2, textColor, 2);
}
<commit_msg>Extract constants<commit_after>#include <opencv2/core.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/dpm.hpp>
#include <opencv2/tracking.hpp>

#include <cstring>
#include <fstream>
#include <iostream>
#include <stdio.h>

using namespace cv;
using namespace cv::dpm;
using namespace std;

void drawDPMBoxes(Mat &frame,
                  vector<DPMDetector::ObjectDetection> ds,
                  Scalar color,
                  string text);

void drawKCFBoxes(Mat &frame,
                  Rect rect,
                  Scalar color,
                  string text);

bool write_count(int count);

static const float LOW_PASS = 0.5;
static const int FRAME_WIDTH = 320;
static const int FRAME_HEIGHT = 240;
static const string CLEAR_FILE = "/opt/mz-bicycle-commuter/reset";
static const string LEFT_OUTPUT_FILE = "/opt/mz-bicycle-commuter/left.count";

int main( int argc, char** argv )
{
    bool ENTER_LEAVE = true;
    bool FRAMES_FIRST = true;

    Mat frame;
    Mat image;
    const char* keys =
    {
        "{@model_path    | | Path of the DPM cascade model}"
        "{@video_source    | | Video Source}"
    };

    CommandLineParser parser(argc, argv, keys);
    string model_path(parser.get<string>(0));
    bool show_image (parser.get<bool>(1));

    // init DPM
    Ptr<DPMDetector> detector = \
    DPMDetector::create(vector<string>(1, model_path));
    vector<DPMDetector::ObjectDetection> ds;

    // init KCF
    Ptr<Tracker> tracker;
    Rect2d roi;
    Rect result; // Tracker results
    int count = 0;
    //use web camera
    VideoCapture capture(0);
    capture.set(CV_CAP_PROP_FRAME_WIDTH, FRAME_WIDTH);
    capture.set(CV_CAP_PROP_FRAME_HEIGHT, FRAME_HEIGHT);
  //  capture.set(CV_CAP_PROP_CONVERT_RGB, false);
	  capture.set(CV_CAP_PROP_FPS, 10);
    double fps = capture.get(CAP_PROP_FPS);

     cout << fps << endl;

    if( model_path.empty() )
    {
        cerr << "Fail to open model file!" << endl;
        return -1;
    }

    if ( !capture.isOpened() )
    {
        cerr << "Fail to open default camera (0)!" << endl;
        return -1;
    }

    // create window
    if (show_image) {
        namedWindow("tracker", 1);
    }
    int frame_count = 10;
    while (true){
        //get the frame
        capture >> frame;

        if ( frame.empty() ){
            cerr << "Fail to get video!" << endl;
            break;
        }

        //DPM detection
        if( ENTER_LEAVE )
        {

            if ((++frame_count % 10) != 0) {
              // cout << "skip" << endl;
              continue;
            }
            // cout << "no skip" << endl;

            frame_count = 0;

            double t = (double) getTickCount(); //start time

            frame.copyTo(image);

            // detection
            detector->detect(image, ds);

            ds.erase(std::remove_if(ds.begin(),
                                    ds.end(),
                                    [&](const DPMDetector::ObjectDetection& o)
                                    {return o.score < LOW_PASS;}
                                    ),
                     ds.end());
            if (!ds.empty())
            {
                for (const auto i: ds)
                    std::cout << i.score << ' ';
                cout << endl;

                ENTER_LEAVE = false;
                FRAMES_FIRST = true;
            }

            t = ((double) getTickCount() - t)/getTickFrequency(); //elapsed time
            string text = format("%0.1f fps", 1.0/t); //calculate fps

            // draw the tracked object
            Scalar color(0,0,255);
            drawDPMBoxes(frame, ds, color, text);
        } else {

            //KCF tracking
            double t = (double) getTickCount(); //start time
            if ( FRAMES_FIRST )
            {
                // get bounding box
                roi = ds[0].rect;

                // initialize the tracker
                tracker = Tracker::create("KCF");
                bool success = tracker->init(frame,roi);

                FRAMES_FIRST = !success ;
            }

            // Update
            else{

                // update the tracking result
                bool was_successful = tracker->update(frame,roi);

                if (!was_successful) {
                    continue;
                }
                result = roi;
                //DPM model detect UAV's leave
                int x_value = FRAME_WIDTH - result.x - result.width/2;
                int y_value = FRAME_HEIGHT - result.y - result.height/2;
                if (!(result.x > 0 && result.y > 0 && x_value > 0 && y_value > 0)){
                    ENTER_LEAVE = true;
                    count++;
                    bool reset_count = write_count(count);
                     string count_text;
                    if (reset_count) {
                        count = 0;
                        count_text = "Count was reset";
                    } else {
                        count_text  = format("%ld bicycles!", count);
                    }

                    cout << count_text << endl;

                }
            }
            t = ((double) getTickCount() - t)/getTickFrequency(); //elapsed time
            string text = format("%0.1f fps", 1.0/t); //calculate fps

            // draw the tracked object
            Scalar color(0,0,255);
            drawKCFBoxes(frame, roi, color, text);
        }

        // show image with the tracked object
        if(show_image) {
            imshow("tracker",frame);
        }
        if(waitKey(1)==27)break;
    }
    return 0;
}

bool write_count(int count)
{
    ofstream resultsFile;
    bool should_clear = std::ifstream(CLEAR_FILE).good();

    int file_count = should_clear ? 1 : count;
    resultsFile.open(LEFT_OUTPUT_FILE);
    resultsFile << file_count  << endl;
    resultsFile.close();
    if(should_clear) {
        remove(CLEAR_FILE.c_str());
    }

    return should_clear;
}

void drawDPMBoxes(Mat &frame,
                  vector<DPMDetector::ObjectDetection> ds,
                  Scalar color,
                  string text)
{
    for (unsigned int i = 0; i < ds.size(); i++)
    {
        rectangle(frame, ds[i].rect, color, 2);
    }

    // draw text on image
    Scalar textColor(255,0,0);
    putText(frame, text, Point(10,50), FONT_HERSHEY_PLAIN, 2, textColor, 2);
}

void drawKCFBoxes(Mat &frame,
                  Rect rect,
                  Scalar color,
                  string text)
{
    rectangle(frame, rect, color, 2);

    // draw text on image
    Scalar textColor(255,0,0);
    putText(frame, text, Point(10,50), FONT_HERSHEY_PLAIN, 2, textColor, 2);
}
<|endoftext|>


<commit_before>/*
    This file is part of KContactManager.
    Copyright (c) 1996-2002 Mirko Boehm <mirko@kde.org>
                            Tobias Koenig <tokoe@kde.org>

    Copyright (c) 2009 Laurent Montel <montel@kde.org>
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "printingwizard.h"

#include <QtGui/QPushButton>
#include <QtGui/QPrinter>

#include <kabc/addresseelist.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kglobal.h>
#include <klocale.h>

#include "globalcontactmodel.h"
#include "contactstreemodel.h"
#include "entitytreemodel.h"
#include "entityfilterproxymodel.h"

// including the styles
#include "detailledstyle.h"
#include "mikesstyle.h"
#include "ringbinderstyle.h"

#include "printprogress.h"
#include "printstyle.h"
#include "printsortmode.h"

using namespace KABPrinting;

PrintingWizard::PrintingWizard( QPrinter *printer, Akonadi::EntityFilterProxyModel *itemTree, QWidget *parent )
  : KAssistantDialog( parent ), mPrinter( printer ), mItemTree(itemTree), mStyle( 0 )
{
  mSelectionPage = new SelectionPage( this );
#if 0 //sebsauer
  mSelectionPage->setUseSelection( !contacts.isEmpty() );
#endif
  KPageWidgetItem *mSelectionPageItem = new KPageWidgetItem( mSelectionPage, i18n("Choose Contacts to Print") );
  addPage( mSelectionPageItem );

  setAppropriate( mSelectionPageItem, true );

  mStylePage = new StylePage( this );
  connect( mStylePage, SIGNAL( styleChanged(int) ), SLOT( slotStyleSelected(int) ) );
  addPage( mStylePage, i18n("Choose Printing Style") );

  registerStyles();

  if ( mStyleFactories.count() > 0 )
    slotStyleSelected( 0 );
}

PrintingWizard::~PrintingWizard()
{
}

void PrintingWizard::accept()
{
  print();
  close();
}

void PrintingWizard::registerStyles()
{
  mStyleFactories.append( new DetailledPrintStyleFactory( this ) );
  mStyleFactories.append( new MikesStyleFactory( this ) );
  mStyleFactories.append( new RingBinderPrintStyleFactory( this ) );

  mStylePage->clearStyleNames();
  for ( int i = 0; i < mStyleFactories.count(); ++i )
    mStylePage->addStyleName( mStyleFactories.at( i )->description() );
}

void PrintingWizard::slotStyleSelected( int index )
{
  if ( index < 0 || index >= mStyleFactories.count() )
    return;

  //enableButton( KDialog::User1, false ); // finish button

  if ( mStyle )
    mStyle->hidePages();

  mStyle = mStyleList.value( index );
  if ( !mStyle ) {
    PrintStyleFactory *factory = mStyleFactories.at( index );
    kDebug(5720) <<"PrintingWizardImpl::slotStyleSelected:"
                  << "creating print style"
                  << factory->description();
    mStyle = factory->create();
    mStyleList.insert( index, mStyle );
  }

  mStyle->showPages();

  mStylePage->setPreview( mStyle->preview() );

  //setFinishEnabled( page( pageCount() - 1 ), true );

  if ( mStyle->preferredSortField() != 0 ) {
#warning "port me"
    mStylePage->setSortField( mStyle->preferredSortField() );
#if 0
    mStylePage->setSortAscending( mStyle->preferredSortType() );
#endif
  }
}

QPrinter* PrintingWizard::printer()
{
  return mPrinter;
}

void PrintingWizard::print()
{
  // create and show print progress widget:
  PrintProgress *progress = new PrintProgress( this );
  KPageWidgetItem *progressItem = new KPageWidgetItem( progress, i18n( "Print Progress" ) );
  addPage( progressItem );
  setCurrentPage( progressItem );
  kapp->processEvents();

  // prepare list of contacts to print:

  KABC::AddresseeList list;
  if ( mStyle != 0 ) {
    if ( mSelectionPage->useSelection() ) {
#if 0
      QStringList::ConstIterator it;
      for ( it = mSelection.constBegin(); it != mSelection.constEnd(); ++it ) {
        KABC::Addressee addr = addressBook()->findByUid( *it );
        if ( !addr.isEmpty() )
          list.append( addr );
      }
#else
      Q_ASSERT(false);
#endif
    } else if ( mSelectionPage->useFilters() ) {
      //TODO ? or remove it it's not necessary
    } else if ( mSelectionPage->useCategories() ) {
#if 0
      QStringList categories = mSelectionPage->categories();
      KABC::AddressBook::ConstIterator it;
      for ( it = addressBook()->constBegin(); it != addressBook()->constEnd(); ++it ) {
        const QStringList tmp( (*it).categories() );
        QStringList::ConstIterator tmpIt;
        for ( tmpIt = tmp.constBegin(); tmpIt != tmp.constEnd(); ++tmpIt )
          if ( categories.contains( *tmpIt ) ) {
            list.append( *it );
            break;
          }
      }
#else
      Q_ASSERT(false);
#endif
    } else {
      // create a string list of all entries:
      for(int row = 0; row < mItemTree->rowCount(); ++row) {
        const QModelIndex index = mItemTree->index( row, 0 );
        const Akonadi::Item item = mItemTree->data( index, Akonadi::EntityTreeModel::ItemRole ).value<Akonadi::Item>();
        Q_ASSERT( item.isValid() );
        const KABC::Addressee adr = item.payload<KABC::Addressee>();
        list.append( adr );
      }
    }

    list.setReverseSorting( !mStylePage->sortAscending() );
    PrintSortMode sortMode( mStylePage->sortField() );
    list.sortByMode( &sortMode );
  }

  kDebug(5720) <<"PrintingWizardImpl::print: printing"
                << list.count() << "contacts.";
  // ... print:
  enableButton( KDialog::User3, false ); // back button
  enableButton( KDialog::Cancel, false );
  mStyle->print( list, progress );
}

#include "printingwizard.moc"
<commit_msg>don't allow to select something that doesn't work (yet)<commit_after>/*
    This file is part of KContactManager.
    Copyright (c) 1996-2002 Mirko Boehm <mirko@kde.org>
                            Tobias Koenig <tokoe@kde.org>

    Copyright (c) 2009 Laurent Montel <montel@kde.org>
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "printingwizard.h"

#include <QtGui/QPushButton>
#include <QtGui/QPrinter>

#include <kabc/addresseelist.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kglobal.h>
#include <klocale.h>

#include "globalcontactmodel.h"
#include "contactstreemodel.h"
#include "entitytreemodel.h"
#include "entityfilterproxymodel.h"

// including the styles
#include "detailledstyle.h"
#include "mikesstyle.h"
#include "ringbinderstyle.h"

#include "printprogress.h"
#include "printstyle.h"
#include "printsortmode.h"

using namespace KABPrinting;

PrintingWizard::PrintingWizard( QPrinter *printer, Akonadi::EntityFilterProxyModel *itemTree, QWidget *parent )
  : KAssistantDialog( parent ), mPrinter( printer ), mItemTree(itemTree), mStyle( 0 )
{
  mSelectionPage = new SelectionPage( this );
#if 0 //sebsauer
  mSelectionPage->setUseSelection( !contacts.isEmpty() );
#else
  mSelectionPage->setUseSelection( false );
#endif
  KPageWidgetItem *mSelectionPageItem = new KPageWidgetItem( mSelectionPage, i18n("Choose Contacts to Print") );
  addPage( mSelectionPageItem );

  setAppropriate( mSelectionPageItem, true );

  mStylePage = new StylePage( this );
  connect( mStylePage, SIGNAL( styleChanged(int) ), SLOT( slotStyleSelected(int) ) );
  addPage( mStylePage, i18n("Choose Printing Style") );

  registerStyles();

  if ( mStyleFactories.count() > 0 )
    slotStyleSelected( 0 );
}

PrintingWizard::~PrintingWizard()
{
}

void PrintingWizard::accept()
{
  print();
  close();
}

void PrintingWizard::registerStyles()
{
  mStyleFactories.append( new DetailledPrintStyleFactory( this ) );
  mStyleFactories.append( new MikesStyleFactory( this ) );
  mStyleFactories.append( new RingBinderPrintStyleFactory( this ) );

  mStylePage->clearStyleNames();
  for ( int i = 0; i < mStyleFactories.count(); ++i )
    mStylePage->addStyleName( mStyleFactories.at( i )->description() );
}

void PrintingWizard::slotStyleSelected( int index )
{
  if ( index < 0 || index >= mStyleFactories.count() )
    return;

  //enableButton( KDialog::User1, false ); // finish button

  if ( mStyle )
    mStyle->hidePages();

  mStyle = mStyleList.value( index );
  if ( !mStyle ) {
    PrintStyleFactory *factory = mStyleFactories.at( index );
    kDebug(5720) <<"PrintingWizardImpl::slotStyleSelected:"
                  << "creating print style"
                  << factory->description();
    mStyle = factory->create();
    mStyleList.insert( index, mStyle );
  }

  mStyle->showPages();

  mStylePage->setPreview( mStyle->preview() );

  //setFinishEnabled( page( pageCount() - 1 ), true );

  if ( mStyle->preferredSortField() != 0 ) {
#warning "port me"
    mStylePage->setSortField( mStyle->preferredSortField() );
#if 0
    mStylePage->setSortAscending( mStyle->preferredSortType() );
#endif
  }
}

QPrinter* PrintingWizard::printer()
{
  return mPrinter;
}

void PrintingWizard::print()
{
  // create and show print progress widget:
  PrintProgress *progress = new PrintProgress( this );
  KPageWidgetItem *progressItem = new KPageWidgetItem( progress, i18n( "Print Progress" ) );
  addPage( progressItem );
  setCurrentPage( progressItem );
  kapp->processEvents();

  // prepare list of contacts to print:

  KABC::AddresseeList list;
  if ( mStyle != 0 ) {
    if ( mSelectionPage->useSelection() ) {
#if 0
      QStringList::ConstIterator it;
      for ( it = mSelection.constBegin(); it != mSelection.constEnd(); ++it ) {
        KABC::Addressee addr = addressBook()->findByUid( *it );
        if ( !addr.isEmpty() )
          list.append( addr );
      }
#else
      Q_ASSERT(false);
#endif
    } else if ( mSelectionPage->useFilters() ) {
      //TODO ? or remove it it's not necessary
    } else if ( mSelectionPage->useCategories() ) {
#if 0
      QStringList categories = mSelectionPage->categories();
      KABC::AddressBook::ConstIterator it;
      for ( it = addressBook()->constBegin(); it != addressBook()->constEnd(); ++it ) {
        const QStringList tmp( (*it).categories() );
        QStringList::ConstIterator tmpIt;
        for ( tmpIt = tmp.constBegin(); tmpIt != tmp.constEnd(); ++tmpIt )
          if ( categories.contains( *tmpIt ) ) {
            list.append( *it );
            break;
          }
      }
#else
      Q_ASSERT(false);
#endif
    } else {
      // create a string list of all entries:
      for(int row = 0; row < mItemTree->rowCount(); ++row) {
        const QModelIndex index = mItemTree->index( row, 0 );
        const Akonadi::Item item = mItemTree->data( index, Akonadi::EntityTreeModel::ItemRole ).value<Akonadi::Item>();
        Q_ASSERT( item.isValid() );
        const KABC::Addressee adr = item.payload<KABC::Addressee>();
        list.append( adr );
      }
    }

    list.setReverseSorting( !mStylePage->sortAscending() );
    PrintSortMode sortMode( mStylePage->sortField() );
    list.sortByMode( &sortMode );
  }

  kDebug(5720) <<"PrintingWizardImpl::print: printing"
                << list.count() << "contacts.";
  // ... print:
  enableButton( KDialog::User3, false ); // back button
  enableButton( KDialog::Cancel, false );
  mStyle->print( list, progress );
}

#include "printingwizard.moc"
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

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

#include "otbSensorModelWrapper.h"

#include "projection/ossimProjection.h"
#include "projection/ossimSensorModelFactory.h"
#include "ossim/ossimPluginProjectionFactory.h"

//TODO remove this->

namespace otb
{

SensorModelWrapper::SensorModelWrapper():
  m_SensorModel(NULL), m_UseDEM(false), m_Epsilon(0.0001),  m_NbIter(1) // FIXME keeping the original value but...
{
  m_DEMHandler = DEMHandler::New();
}

SensorModelWrapper::~SensorModelWrapper()
{
  if (m_SensorModel != NULL)
    {
    delete m_SensorModel;
    m_SensorModel = NULL;
    }
}

void SensorModelWrapper::CreateProjection(const ImageKeywordlist& image_kwl)
{
  ossimKeywordlist geom;

  image_kwl.convertToOSSIMKeywordlist(geom);
  otbMsgDevMacro(<< "CreateProjection()");
  otbMsgDevMacro(<< "* type: " << geom.find("type"));

  m_SensorModel = ossimSensorModelFactory::instance()->createProjection(geom);
  if (m_SensorModel == NULL)
    {
      m_SensorModel = ossimplugins::ossimPluginProjectionFactory::instance()->createProjection(geom);
    }
}

bool SensorModelWrapper::IsValidSensorModel()
{
  if (m_SensorModel == NULL)
    {
      return false;
    }
  else
    {
      return true;
    }
}

void SensorModelWrapper::SetDEMDirectory(const std::string& directory)
{
  m_DEMHandler->OpenDEMDirectory(directory);
  m_UseDEM = true;
}

void SensorModelWrapper::ForwardTransformPoint(double x, double y, double z,
                                               double& lon, double& lat, double& h) const
{
  ossimDpt ossimPoint(x, y);

  // Calculation
  ossimGpt ossimGPoint;

  if (this->m_SensorModel == NULL)
    {
    itkExceptionMacro(<< "ForwardTransformPoint(): Invalid Model pointer m_SensorModel == NULL !");
    }

  //Use of DEM: need iteration to reach the correct point
  if (this->m_UseDEM)
    {
    this->m_SensorModel->lineSampleToWorld(ossimPoint, ossimGPoint);
    ossimGpt ossimGPointRef = ossimGPoint;
    double height(0.), heightTmp(0.);
    double                diffHeight = 100; // arbitrary value
    itk::Point<double, 2> currentPoint;
    int                   nbIter = 0;

    otbMsgDevMacro(<< "USING DEM ! ");

    while ((diffHeight > m_Epsilon) && (nbIter < m_NbIter))
      {
      otbMsgDevMacro(<< "Iter " << nbIter);

      if (nbIter != 0) height = heightTmp;

      heightTmp = this->m_DEMHandler->GetHeightAboveMSL(lon, lat);

      this->m_SensorModel->lineSampleHeightToWorld(ossimPoint, heightTmp, ossimGPointRef);

      diffHeight = fabs(heightTmp - height);

      ++nbIter;
      }
    ossimGPoint = ossimGPointRef;
    }
  //Altitude of the point is provided (in the sensor coordinate) could be an
  //average elevation
  else if (z != -32768)
    {
    this->m_SensorModel->lineSampleHeightToWorld(ossimPoint, z, ossimGPoint);
    }
  //Otherwise, just don't consider the altitude
  else
    {
    this->m_SensorModel->lineSampleToWorld(ossimPoint, ossimGPoint);
    }

  lon = ossimGPoint.lon;
  lat = ossimGPoint.lat;
  h = ossimGPoint.hgt;
}

void SensorModelWrapper::InverseTransformPoint(double lon, double lat, double h,
                                               double& x, double& y, double& z) const
{
  ossimGpt ossimGPoint(lat, lon);

  if (this->m_UseDEM)
    {
    double height = this->m_DEMHandler->GetHeightAboveMSL(lon, lat);
    ossimGPoint.height(height);
    }
  else if (h != -32768)
    {
    ossimGPoint.height(h);
    }

  ossimDpt ossimDPoint;

  if (this->m_SensorModel == NULL)
    {
    itkExceptionMacro(<< "InverseTransformPoint(): Invalid Model pointer m_SensorModel == NULL !");
    }

  if (ossimGPoint.hgt == -32768)
    {
    ossimGPoint.hgt = ossim::nan();
    }

  // Note: the -32768 is only here to show unknown altitude and should never be
  // passed to ossim
  assert(ossim::isnan(ossimGPoint.hgt) || (ossimGPoint.hgt > -1000));

  this->m_SensorModel->worldToLineSample(ossimGPoint, ossimDPoint); //"worldToLineSample" call "lineSampleHeightToWorld" method for take in care elevation information.

  x = ossimDPoint.x;
  y = ossimDPoint.y;
  z = ossimGPoint.height();
}

ossimProjection* SensorModelWrapper::GetOssimModel() //FIXME temporary only
{
  return m_SensorModel;
}

}
<commit_msg>BUG: lon lat were unitialised, and therefore the loop did not converge to an acceptable value<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

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

#include "otbSensorModelWrapper.h"

#include "projection/ossimProjection.h"
#include "projection/ossimSensorModelFactory.h"
#include "ossim/ossimPluginProjectionFactory.h"

//TODO remove this->

namespace otb
{

SensorModelWrapper::SensorModelWrapper():
  m_SensorModel(NULL), m_UseDEM(false), m_Epsilon(0.0001),  m_NbIter(1) // FIXME keeping the original value but...
{
  m_DEMHandler = DEMHandler::New();
}

SensorModelWrapper::~SensorModelWrapper()
{
  if (m_SensorModel != NULL)
    {
    delete m_SensorModel;
    m_SensorModel = NULL;
    }
}

void SensorModelWrapper::CreateProjection(const ImageKeywordlist& image_kwl)
{
  ossimKeywordlist geom;

  image_kwl.convertToOSSIMKeywordlist(geom);
  otbMsgDevMacro(<< "CreateProjection()");
  otbMsgDevMacro(<< "* type: " << geom.find("type"));

  m_SensorModel = ossimSensorModelFactory::instance()->createProjection(geom);
  if (m_SensorModel == NULL)
    {
      m_SensorModel = ossimplugins::ossimPluginProjectionFactory::instance()->createProjection(geom);
    }
}

bool SensorModelWrapper::IsValidSensorModel()
{
  if (m_SensorModel == NULL)
    {
      return false;
    }
  else
    {
      return true;
    }
}

void SensorModelWrapper::SetDEMDirectory(const std::string& directory)
{
  m_DEMHandler->OpenDEMDirectory(directory);
  m_UseDEM = true;
}

void SensorModelWrapper::ForwardTransformPoint(double x, double y, double z,
                                               double& lon, double& lat, double& h) const
{
  ossimDpt ossimPoint(x, y);

  // Calculation
  ossimGpt ossimGPoint;

  if (this->m_SensorModel == NULL)
    {
    itkExceptionMacro(<< "ForwardTransformPoint(): Invalid Model pointer m_SensorModel == NULL !");
    }

  //Use of DEM: need iteration to reach the correct point
  if (this->m_UseDEM)
    {
    this->m_SensorModel->lineSampleToWorld(ossimPoint, ossimGPoint);
    lon = ossimGPoint.lon;
    lat = ossimGPoint.lat;

    ossimGpt ossimGPointRef = ossimGPoint;
    double height(0.), heightTmp(0.);
    double                diffHeight = 100; // arbitrary value
    itk::Point<double, 2> currentPoint;
    int                   nbIter = 0;

    otbMsgDevMacro(<< "USING DEM ! ");

    while ((diffHeight > m_Epsilon) && (nbIter < m_NbIter))
      {
      otbMsgDevMacro(<< "Iter " << nbIter);

      if (nbIter != 0) height = heightTmp;

      heightTmp = this->m_DEMHandler->GetHeightAboveMSL(lon, lat);

      this->m_SensorModel->lineSampleHeightToWorld(ossimPoint, heightTmp, ossimGPointRef);

      diffHeight = fabs(heightTmp - height);

      ++nbIter;
      }
    ossimGPoint = ossimGPointRef;
    }
  //Altitude of the point is provided (in the sensor coordinate) could be an
  //average elevation
  else if (z != -32768)
    {
    this->m_SensorModel->lineSampleHeightToWorld(ossimPoint, z, ossimGPoint);
    }
  //Otherwise, just don't consider the altitude
  else
    {
    this->m_SensorModel->lineSampleToWorld(ossimPoint, ossimGPoint);
    }

  lon = ossimGPoint.lon;
  lat = ossimGPoint.lat;
  h = ossimGPoint.hgt;
}

void SensorModelWrapper::InverseTransformPoint(double lon, double lat, double h,
                                               double& x, double& y, double& z) const
{
  ossimGpt ossimGPoint(lat, lon);

  if (this->m_UseDEM)
    {
    double height = this->m_DEMHandler->GetHeightAboveMSL(lon, lat);
    ossimGPoint.height(height);
    }
  else if (h != -32768)
    {
    ossimGPoint.height(h);
    }

  ossimDpt ossimDPoint;

  if (this->m_SensorModel == NULL)
    {
    itkExceptionMacro(<< "InverseTransformPoint(): Invalid Model pointer m_SensorModel == NULL !");
    }

  if (ossimGPoint.hgt == -32768)
    {
    ossimGPoint.hgt = ossim::nan();
    }

  // Note: the -32768 is only here to show unknown altitude and should never be
  // passed to ossim
  assert(ossim::isnan(ossimGPoint.hgt) || (ossimGPoint.hgt > -1000));

  this->m_SensorModel->worldToLineSample(ossimGPoint, ossimDPoint); //"worldToLineSample" call "lineSampleHeightToWorld" method for take in care elevation information.

  x = ossimDPoint.x;
  y = ossimDPoint.y;
  z = ossimGPoint.height();
}

ossimProjection* SensorModelWrapper::GetOssimModel() //FIXME temporary only
{
  return m_SensorModel;
}

}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include "uno/mapping.h"

#include <typeinfo>
#include <exception>
#include <cstddef>

// from opensource.apple.com: libcppabi-24.4/include/rtti.h
#include "rtti.h"

// from opensource.apple.com: libcppabi-24.4/include/unwind-cxx.h
#include "unwind-cxx.h"

// Import the __cxxabiv1 a.k.a. "abi" namespace
using namespace abi;

namespace CPPU_CURRENT_NAMESPACE
{
    void dummy_can_throw_anything( char const * );

    void raiseException(
        uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );

    void fillUnoException(
        __cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno );

    bool isSimpleReturnType(typelib_TypeDescription * pTD, bool recursive = false);
}

namespace arm
{
    enum armlimits {
#if defined(__arm)
        MAX_GPR_REGS = 4,
        MAX_FPR_REGS = 8
#elif defined(__arm64)
        MAX_GPR_REGS = 8,
        MAX_FPR_REGS = 8
#else
#error wtf
#endif
    };
    bool return_in_x8( typelib_TypeDescriptionReference *pTypeRef );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fix build break for (32-bit) arm<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include "uno/mapping.h"

#include <typeinfo>
#include <exception>
#include <cstddef>

// from opensource.apple.com: libcppabi-24.4/include/rtti.h
#include "rtti.h"

// from opensource.apple.com: libcppabi-24.4/include/unwind-cxx.h
#include "unwind-cxx.h"

// Import the __cxxabiv1 a.k.a. "abi" namespace
using namespace abi;

namespace CPPU_CURRENT_NAMESPACE
{
    void dummy_can_throw_anything( char const * );

    void raiseException(
        uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );

    void fillUnoException(
        __cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno );

    bool isSimpleReturnType(typelib_TypeDescription * pTD, bool recursive = false);
}

namespace arm
{
#if defined(__arm)
    enum armlimits {
        MAX_GPR_REGS = 4,
        MAX_FPR_REGS = 8
    };
    bool return_in_hidden_param( typelib_TypeDescriptionReference *pTypeRef );
#elif defined(__arm64)
    enum armlimits {
        MAX_GPR_REGS = 8,
        MAX_FPR_REGS = 8
    };
    bool return_in_x8( typelib_TypeDescriptionReference *pTypeRef );
#else
#error wtf
#endif
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>//===- PublicsStream.cpp - PDB Public Symbol Stream -----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The data structures defined in this file are based on the reference
// implementation which is available at
// https://github.com/Microsoft/microsoft-pdb/blob/master/PDB/dbi/gsi.h
//
// When you are reading the reference source code, you'd find the
// information below useful.
//
//  - ppdb1->m_fMinimalDbgInfo seems to be always true.
//  - SMALLBUCKETS macro is defined.
//
// The reference doesn't compile, so I learned just by reading code.
// It's not guaranteed to be correct.
//
//===----------------------------------------------------------------------===//

#include "llvm/DebugInfo/PDB/Raw/PublicsStream.h"

#include "llvm/DebugInfo/CodeView/CodeView.h"
#include "llvm/DebugInfo/CodeView/TypeRecord.h"
#include "llvm/DebugInfo/PDB/Raw/MappedBlockStream.h"
#include "llvm/DebugInfo/PDB/Raw/RawConstants.h"
#include "llvm/DebugInfo/PDB/Raw/RawError.h"
#include "llvm/DebugInfo/PDB/Raw/StreamReader.h"

#include "llvm/ADT/BitVector.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/MathExtras.h"

using namespace llvm;
using namespace llvm::support;
using namespace llvm::pdb;

static const unsigned IPHR_HASH = 4096;

// This is PSGSIHDR struct defined in
// https://github.com/Microsoft/microsoft-pdb/blob/master/PDB/dbi/gsi.h
struct PublicsStream::HeaderInfo {
  ulittle32_t SymHash;
  ulittle32_t AddrMap;
  ulittle32_t NumThunks;
  ulittle32_t SizeOfThunk;
  ulittle16_t ISectThunkTable;
  char Padding[2];
  ulittle32_t OffThunkTable;
  ulittle32_t NumSections;
};

// This is GSIHashHdr struct defined in
struct PublicsStream::GSIHashHeader {
  enum {
    HdrSignature = -1,
    HdrVersion = 0xeffe0000 + 19990810,
  };
  ulittle32_t VerSignature;
  ulittle32_t VerHdr;
  ulittle32_t HrSize;
  ulittle32_t NumBuckets;
};

struct PublicsStream::HRFile {
  ulittle32_t Off;
  ulittle32_t CRef;
};

// This struct is defined as "SO" in langapi/include/pdb.h.
namespace {
struct SectionOffset {
  ulittle32_t Off;
  ulittle16_t Isect;
  char Padding[2];
};
}

PublicsStream::PublicsStream(PDBFile &File, uint32_t StreamNum)
    : StreamNum(StreamNum), Stream(StreamNum, File) {}

PublicsStream::~PublicsStream() {}

uint32_t PublicsStream::getSymHash() const { return Header->SymHash; }
uint32_t PublicsStream::getAddrMap() const { return Header->AddrMap; }

// Publics stream contains fixed-size headers and a serialized hash table.
// This implementation is not complete yet. It reads till the end of the
// stream so that we verify the stream is at least not corrupted. However,
// we skip over the hash table which we believe contains information about
// public symbols.
Error PublicsStream::reload() {
  StreamReader Reader(Stream);

  // Check stream size.
  if (Reader.bytesRemaining() < sizeof(HeaderInfo) + sizeof(GSIHashHeader))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Publics Stream does not contain a header.");

  // Read PSGSIHDR and GSIHashHdr structs.
  Header.reset(new HeaderInfo());
  if (Reader.readObject(Header.get()))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Publics Stream does not contain a header.");
  HashHdr.reset(new GSIHashHeader());
  if (Reader.readObject(HashHdr.get()))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Publics Stream does not contain a header.");

  // An array of HRFile follows. Read them.
  if (HashHdr->HrSize % sizeof(HRFile))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Invalid HR array size.");
  std::vector<HRFile> HRs(HashHdr->HrSize / sizeof(HRFile));
  if (auto EC = Reader.readArray<HRFile>(HRs))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Could not read an HR array");

  // A bitmap of a fixed length follows.
  size_t BitmapSizeInBits = alignTo(IPHR_HASH + 1, 32);
  std::vector<uint8_t> Bitmap(BitmapSizeInBits / 8);
  if (auto EC = Reader.readArray<uint8_t>(Bitmap))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Could not read a bitmap.");
  for (uint8_t B : Bitmap)
    NumBuckets += countPopulation(B);

  // We don't yet understand the following data structures completely,
  // but we at least know the types and sizes. Here we are trying
  // to read the stream till end so that we at least can detect
  // corrupted streams.

  // Hash buckets follow.
  HashBuckets.resize(NumBuckets);
  if (auto EC = Reader.readArray<uint32_t>(HashBuckets))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Hash buckets corrupted.");

  // Something called "address map" follows.
  AddressMap.resize(Header->AddrMap / sizeof(uint32_t));
  if (auto EC = Reader.readArray<uint32_t>(AddressMap))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Could not read an address map.");

  // Something called "thunk map" follows.
  ThunkMap.resize(Header->NumThunks);
  if (auto EC = Reader.readArray<uint32_t>(ThunkMap))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Could not read a thunk map.");

  // Something called "section map" follows.
  std::vector<SectionOffset> SectionMap(Header->NumSections);
  if (auto EC = Reader.readArray<SectionOffset>(SectionMap))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Could not read a section map.");

  if (Reader.bytesRemaining() > 0)
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Corrupted publics stream.");
  return Error::success();
}
<commit_msg>Attempt to fix pdbdump-headers.test on big-endian hosts after r269861.<commit_after>//===- PublicsStream.cpp - PDB Public Symbol Stream -----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The data structures defined in this file are based on the reference
// implementation which is available at
// https://github.com/Microsoft/microsoft-pdb/blob/master/PDB/dbi/gsi.h
//
// When you are reading the reference source code, you'd find the
// information below useful.
//
//  - ppdb1->m_fMinimalDbgInfo seems to be always true.
//  - SMALLBUCKETS macro is defined.
//
// The reference doesn't compile, so I learned just by reading code.
// It's not guaranteed to be correct.
//
//===----------------------------------------------------------------------===//

#include "llvm/DebugInfo/PDB/Raw/PublicsStream.h"

#include "llvm/DebugInfo/CodeView/CodeView.h"
#include "llvm/DebugInfo/CodeView/TypeRecord.h"
#include "llvm/DebugInfo/PDB/Raw/MappedBlockStream.h"
#include "llvm/DebugInfo/PDB/Raw/RawConstants.h"
#include "llvm/DebugInfo/PDB/Raw/RawError.h"
#include "llvm/DebugInfo/PDB/Raw/StreamReader.h"

#include "llvm/ADT/BitVector.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/MathExtras.h"

using namespace llvm;
using namespace llvm::support;
using namespace llvm::pdb;

static const unsigned IPHR_HASH = 4096;

// This is PSGSIHDR struct defined in
// https://github.com/Microsoft/microsoft-pdb/blob/master/PDB/dbi/gsi.h
struct PublicsStream::HeaderInfo {
  ulittle32_t SymHash;
  ulittle32_t AddrMap;
  ulittle32_t NumThunks;
  ulittle32_t SizeOfThunk;
  ulittle16_t ISectThunkTable;
  char Padding[2];
  ulittle32_t OffThunkTable;
  ulittle32_t NumSections;
};

// This is GSIHashHdr struct defined in
struct PublicsStream::GSIHashHeader {
  enum {
    HdrSignature = -1,
    HdrVersion = 0xeffe0000 + 19990810,
  };
  ulittle32_t VerSignature;
  ulittle32_t VerHdr;
  ulittle32_t HrSize;
  ulittle32_t NumBuckets;
};

struct PublicsStream::HRFile {
  ulittle32_t Off;
  ulittle32_t CRef;
};

// This struct is defined as "SO" in langapi/include/pdb.h.
namespace {
struct SectionOffset {
  ulittle32_t Off;
  ulittle16_t Isect;
  char Padding[2];
};
}

PublicsStream::PublicsStream(PDBFile &File, uint32_t StreamNum)
    : StreamNum(StreamNum), Stream(StreamNum, File) {}

PublicsStream::~PublicsStream() {}

uint32_t PublicsStream::getSymHash() const { return Header->SymHash; }
uint32_t PublicsStream::getAddrMap() const { return Header->AddrMap; }

// Publics stream contains fixed-size headers and a serialized hash table.
// This implementation is not complete yet. It reads till the end of the
// stream so that we verify the stream is at least not corrupted. However,
// we skip over the hash table which we believe contains information about
// public symbols.
Error PublicsStream::reload() {
  StreamReader Reader(Stream);

  // Check stream size.
  if (Reader.bytesRemaining() < sizeof(HeaderInfo) + sizeof(GSIHashHeader))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Publics Stream does not contain a header.");

  // Read PSGSIHDR and GSIHashHdr structs.
  Header.reset(new HeaderInfo());
  if (Reader.readObject(Header.get()))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Publics Stream does not contain a header.");
  HashHdr.reset(new GSIHashHeader());
  if (Reader.readObject(HashHdr.get()))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Publics Stream does not contain a header.");

  // An array of HRFile follows. Read them.
  if (HashHdr->HrSize % sizeof(HRFile))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Invalid HR array size.");
  std::vector<HRFile> HRs(HashHdr->HrSize / sizeof(HRFile));
  if (auto EC = Reader.readArray<HRFile>(HRs))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Could not read an HR array");

  // A bitmap of a fixed length follows.
  size_t BitmapSizeInBits = alignTo(IPHR_HASH + 1, 32);
  std::vector<uint8_t> Bitmap(BitmapSizeInBits / 8);
  if (auto EC = Reader.readArray<uint8_t>(Bitmap))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Could not read a bitmap.");
  for (uint8_t B : Bitmap)
    NumBuckets += countPopulation(B);

  // We don't yet understand the following data structures completely,
  // but we at least know the types and sizes. Here we are trying
  // to read the stream till end so that we at least can detect
  // corrupted streams.

  // Hash buckets follow.
  std::vector<ulittle32_t> TempHashBuckets;
  TempHashBuckets.resize(NumBuckets);
  if (auto EC = Reader.readArray<ulittle32_t>(TempHashBuckets))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Hash buckets corrupted.");
  HashBuckets.resize(NumBuckets);
  std::copy(TempHashBuckets.begin(), TempHashBuckets.end(),
            HashBuckets.begin());

  // Something called "address map" follows.
  AddressMap.resize(Header->AddrMap / sizeof(uint32_t));
  if (auto EC = Reader.readArray<uint32_t>(AddressMap))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Could not read an address map.");

  // Something called "thunk map" follows.
  ThunkMap.resize(Header->NumThunks);
  if (auto EC = Reader.readArray<uint32_t>(ThunkMap))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Could not read a thunk map.");

  // Something called "section map" follows.
  std::vector<SectionOffset> SectionMap(Header->NumSections);
  if (auto EC = Reader.readArray<SectionOffset>(SectionMap))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Could not read a section map.");

  if (Reader.bytesRemaining() > 0)
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Corrupted publics stream.");
  return Error::success();
}
<|endoftext|>


<commit_before>//===--- ARCMatchingSet.cpp - ARC Matching Set Builder --------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "arc-sequence-opts"
#include "RefCountState.h"
#include "ARCMatchingSet.h"
#include "swift/Basic/BlotMapVector.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Analysis/ARCAnalysis.h"
#include "swift/SILOptimizer/Analysis/AliasAnalysis.h"
#include "swift/SILOptimizer/Analysis/PostOrderAnalysis.h"
#include "swift/SILOptimizer/Analysis/RCIdentityAnalysis.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/CommandLine.h"

using namespace swift;

//===----------------------------------------------------------------------===//
//                          ARC Matching Set Builder
//===----------------------------------------------------------------------===//

/// Match retains to releases and return whether or not all of the releases
/// were known safe.
Optional<MatchingSetFlags>
ARCMatchingSetBuilder::matchIncrementsToDecrements() {
  MatchingSetFlags Flags = {true, false};

  // For each increment in our list of new increments.
  //
  // FIXME: Refactor this into its own function.
  for (SILInstruction *Increment : NewIncrements) {
    DEBUG(llvm::dbgs() << "    Looking up state for increment: " << *Increment);

    auto BURefCountState = BUMap.find(Increment);
    assert(BURefCountState != BUMap.end() && "Catch this on debug builds.");
    if (BURefCountState == BUMap.end()) {
      DEBUG(llvm::dbgs() << "        FAILURE! Could not find state for "
                            "increment!\n");
      return None;
    }

    DEBUG(llvm::dbgs() << "        SUCCESS! Found state for increment.\n");

    // If we are not tracking a ref count inst for this increment, there is
    // nothing we can pair it with implying we should skip it.
    if (!(*BURefCountState)->second.isTrackingRefCountInst()) {
      DEBUG(llvm::dbgs() << "    SKIPPING INCREMENT! State not tracking any "
                            "instruction.\n");
      continue;
    }

    // We need to be known safe over all increments/decrements we are matching
    // up
    // to ignore insertion points.
    bool BUIsKnownSafe = (*BURefCountState)->second.isKnownSafe();
    DEBUG(llvm::dbgs() << "        KNOWNSAFE: "
                       << (BUIsKnownSafe ? "true" : "false") << "\n");
    Flags.KnownSafe &= BUIsKnownSafe;

    // We can only move instructions if we know that we are not partial. We can
    // still delete instructions in such cases though.
    bool BUIsPartial = (*BURefCountState)->second.isPartial();
    DEBUG(llvm::dbgs() << "        PARTIAL: "
                       << (BUIsPartial ? "true" : "false") << "\n");
    Flags.Partial |= BUIsPartial;

    // Now that we know we have an inst, grab the decrement.
    for (auto DecIter : (*BURefCountState)->second.getInstructions()) {
      SILInstruction *Decrement = DecIter;
      DEBUG(llvm::dbgs() << "        Decrement: " << *Decrement);

      // Now grab the increment matched up with the decrement from the bottom up
      // map.
      // If we can't find it, bail we can't match this increment up with
      // anything.
      auto TDRefCountState = TDMap.find(Decrement);
      if (TDRefCountState == TDMap.end()) {
        DEBUG(llvm::dbgs() << "            FAILURE! Could not find state for "
                              "decrement.\n");
        return None;
      }
      DEBUG(llvm::dbgs() << "            SUCCESS! Found state for "
                            "decrement.\n");

      // Make sure the increment we are looking at is also matched to our
      // decrement.
      // Otherwise bail.
      if (!(*TDRefCountState)->second.isTrackingRefCountInst() ||
          !(*TDRefCountState)->second.containsInstruction(Increment)) {
        DEBUG(
            llvm::dbgs() << "            FAILURE! Not tracking instruction or "
                            "found increment that did not match.\n");
        return None;
      }

      // Add the decrement to the decrement to move set. If we don't insert
      // anything, just continue.
      if (!MatchSet.Decrements.insert(Decrement)) {
        DEBUG(llvm::dbgs()
              << "        SKIPPING! Already processed this decrement\n");
        continue;
      }

      // Collect the increment insertion point if it has one.
      for (auto InsertPt : (*TDRefCountState)->second.getInsertPts()) {
        MatchSet.IncrementInsertPts.insert(InsertPt);
      }
      NewDecrements.push_back(Decrement);
    }
  }

  return Flags;
}

Optional<MatchingSetFlags>
ARCMatchingSetBuilder::matchDecrementsToIncrements() {
  MatchingSetFlags Flags = {true, false};

  // For each increment in our list of new increments.
  //
  // FIXME: Refactor this into its own function.
  for (SILInstruction *Decrement : NewDecrements) {
    DEBUG(llvm::dbgs() << "    Looking up state for decrement: " << *Decrement);

    auto TDRefCountState = TDMap.find(Decrement);
    assert(TDRefCountState != TDMap.end() && "Catch this on debug builds.");
    if (TDRefCountState == TDMap.end()) {
      DEBUG(llvm::dbgs() << "        FAILURE! Could not find state for "
                            "increment!\n");
      return None;
    }

    DEBUG(llvm::dbgs() << "        SUCCESS! Found state for decrement.\n");

    // If we are not tracking a ref count inst for this increment, there is
    // nothing we can pair it with implying we should skip it.
    if (!(*TDRefCountState)->second.isTrackingRefCountInst()) {
      DEBUG(llvm::dbgs() << "    SKIPPING DECREMENT! State not tracking any "
                            "instruction.\n");
      continue;
    }

    // We need to be known safe over all increments/decrements we are matching
    // up
    // to ignore insertion points.
    bool TDIsKnownSafe = (*TDRefCountState)->second.isKnownSafe();
    DEBUG(llvm::dbgs() << "        KNOWNSAFE: "
                       << (TDIsKnownSafe ? "true" : "false") << "\n");
    Flags.KnownSafe &= TDIsKnownSafe;

    // We can only move instructions if we know that we are not partial. We can
    // still delete instructions in such cases though.
    bool TDIsPartial = (*TDRefCountState)->second.isPartial();
    DEBUG(llvm::dbgs() << "        PARTIAL: "
                       << (TDIsPartial ? "true" : "false") << "\n");
    Flags.Partial |= TDIsPartial;

    // Now that we know we have an inst, grab the decrement.
    for (auto IncIter : (*TDRefCountState)->second.getInstructions()) {
      SILInstruction *Increment = IncIter;
      DEBUG(llvm::dbgs() << "        Increment: " << *Increment);

      // Now grab the increment matched up with the decrement from the bottom up
      // map.
      // If we can't find it, bail we can't match this increment up with
      // anything.
      auto BURefCountState = BUMap.find(Increment);
      if (BURefCountState == BUMap.end()) {
        DEBUG(llvm::dbgs() << "            FAILURE! Could not find state for "
                              "increment.\n");
        return None;
      }

      DEBUG(
          llvm::dbgs() << "            SUCCESS! Found state for increment.\n");

      // Make sure the increment we are looking at is also matched to our
      // decrement.
      // Otherwise bail.
      if (!(*BURefCountState)->second.isTrackingRefCountInst() ||
          !(*BURefCountState)->second.containsInstruction(Decrement)) {
        DEBUG(
            llvm::dbgs() << "            FAILURE! Not tracking instruction or "
                            "found increment that did not match.\n");
        return None;
      }

      // Add the decrement to the decrement to move set. If we don't insert
      // anything, just continue.
      if (!MatchSet.Increments.insert(Increment)) {
        DEBUG(llvm::dbgs()
              << "    SKIPPING! Already processed this increment.\n");
        continue;
      }

      // Collect the decrement insertion point if we have one.
      for (auto InsertPtIter : (*BURefCountState)->second.getInsertPts()) {
        MatchSet.DecrementInsertPts.insert(InsertPtIter);
      }
      NewIncrements.push_back(Increment);
    }
  }

  return Flags;
}

/// Visit each retain/release that is matched up to our operand over and over
/// again until we converge by not adding any more to the set which we can move.
/// If we find a situation that we cannot handle, we bail and return false. If
/// we succeed and it is safe to move increment/releases, we return true.
bool ARCMatchingSetBuilder::matchUpIncDecSetsForPtr() {
  bool KnownSafeTD = true;
  bool KnownSafeBU = true;
  bool Partial = false;

  while (true) {
    DEBUG(llvm::dbgs() << "Attempting to match up increments -> decrements:\n");
    // For each increment in our list of new increments, attempt to match them
    // up
    // with decrements and gather the insertion points of the decrements.
    auto Result = matchIncrementsToDecrements();
    if (!Result) {
      DEBUG(llvm::dbgs() << "    FAILED TO MATCH INCREMENTS -> DECREMENTS!\n");
      return false;
    }
    if (!Result->KnownSafe) {
      DEBUG(llvm::dbgs() << "    NOT KNOWN SAFE!\n");
      KnownSafeTD = false;
    }
    if (Result->Partial) {
      DEBUG(llvm::dbgs() << "    IS PARTIAL!\n");
      Partial = true;
    }
    NewIncrements.clear();

    // If we do not have any decrements to attempt to match up with, bail.
    if (NewDecrements.empty())
      break;

    DEBUG(llvm::dbgs() << "Attempting to match up decrements -> increments:\n");
    Result = matchDecrementsToIncrements();
    if (!Result) {
      DEBUG(llvm::dbgs() << "    FAILED TO MATCH DECREMENTS -> INCREMENTS!\n");
      return false;
    }
    if (!Result->KnownSafe) {
      DEBUG(llvm::dbgs() << "    NOT KNOWN SAFE!\n");
      KnownSafeBU = false;
    }
    if (Result->Partial) {
      DEBUG(llvm::dbgs() << "    IS PARTIAL!\n");
      Partial = true;
    }
    NewDecrements.clear();

    // If we do not have any increment to attempt to match up with again, bail.
    if (NewIncrements.empty())
      break;
  }

  bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU);
  if (UnconditionallySafe) {
    DEBUG(llvm::dbgs() << "UNCONDITIONALLY SAFE! DELETING INSTS.\n");
    MatchSet.IncrementInsertPts.clear();
    MatchSet.DecrementInsertPts.clear();
  } else {
    DEBUG(llvm::dbgs() << "NOT UNCONDITIONALLY SAFE!\n");
  }

  bool HaveIncInsertPts = !MatchSet.IncrementInsertPts.empty();
  bool HaveDecInsertPts = !MatchSet.DecrementInsertPts.empty();

  // If we have insertion points and partial merges, return false to avoid
  // control dependency issues.
  if ((HaveIncInsertPts || HaveDecInsertPts) && Partial) {
    DEBUG(llvm::dbgs() << "Found partial merge and insert pts. Bailing!\n");
    return false;
  }

  // If we have insertion points for increments, but not for decrements (or
  // vis-a-versa), return false. This prevents us from inserting retains and
  // removing releases or vis-a-versa.
  if (HaveIncInsertPts != HaveDecInsertPts)
    return false;

  // If we do not have any insertion points but we do have increments, we must
  // be eliminating pairs.
  if (!HaveIncInsertPts && !MatchSet.Increments.empty())
    MatchedPair = true;

  // Success!
  DEBUG(llvm::dbgs() << "SUCCESS! We can move, remove things.\n");
  return true;
}
<commit_msg>Remove some unreachable code. Also add an assertion. NFC<commit_after>//===--- ARCMatchingSet.cpp - ARC Matching Set Builder --------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "arc-sequence-opts"
#include "RefCountState.h"
#include "ARCMatchingSet.h"
#include "swift/Basic/BlotMapVector.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Analysis/ARCAnalysis.h"
#include "swift/SILOptimizer/Analysis/AliasAnalysis.h"
#include "swift/SILOptimizer/Analysis/PostOrderAnalysis.h"
#include "swift/SILOptimizer/Analysis/RCIdentityAnalysis.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/CommandLine.h"

using namespace swift;

//===----------------------------------------------------------------------===//
//                          ARC Matching Set Builder
//===----------------------------------------------------------------------===//

/// Match retains to releases and return whether or not all of the releases
/// were known safe.
Optional<MatchingSetFlags>
ARCMatchingSetBuilder::matchIncrementsToDecrements() {
  MatchingSetFlags Flags = {true, false};

  // For each increment in our list of new increments.
  //
  // FIXME: Refactor this into its own function.
  for (SILInstruction *Increment : NewIncrements) {
    DEBUG(llvm::dbgs() << "    Looking up state for increment: " << *Increment);

    auto BURefCountState = BUMap.find(Increment);
    assert(BURefCountState != BUMap.end() && "Catch this on debug builds.");
    if (BURefCountState == BUMap.end()) {
      DEBUG(llvm::dbgs() << "        FAILURE! Could not find state for "
                            "increment!\n");
      return None;
    }

    DEBUG(llvm::dbgs() << "        SUCCESS! Found state for increment.\n");

    // If we are not tracking a ref count inst for this increment, there is
    // nothing we can pair it with implying we should skip it.
    if (!(*BURefCountState)->second.isTrackingRefCountInst()) {
      DEBUG(llvm::dbgs() << "    SKIPPING INCREMENT! State not tracking any "
                            "instruction.\n");
      continue;
    }

    // We need to be known safe over all increments/decrements we are matching
    // up
    // to ignore insertion points.
    bool BUIsKnownSafe = (*BURefCountState)->second.isKnownSafe();
    DEBUG(llvm::dbgs() << "        KNOWNSAFE: "
                       << (BUIsKnownSafe ? "true" : "false") << "\n");
    Flags.KnownSafe &= BUIsKnownSafe;

    // We can only move instructions if we know that we are not partial. We can
    // still delete instructions in such cases though.
    bool BUIsPartial = (*BURefCountState)->second.isPartial();
    DEBUG(llvm::dbgs() << "        PARTIAL: "
                       << (BUIsPartial ? "true" : "false") << "\n");
    Flags.Partial |= BUIsPartial;

    // Now that we know we have an inst, grab the decrement.
    for (auto DecIter : (*BURefCountState)->second.getInstructions()) {
      SILInstruction *Decrement = DecIter;
      DEBUG(llvm::dbgs() << "        Decrement: " << *Decrement);

      // Now grab the increment matched up with the decrement from the bottom up
      // map.
      // If we can't find it, bail we can't match this increment up with
      // anything.
      auto TDRefCountState = TDMap.find(Decrement);
      if (TDRefCountState == TDMap.end()) {
        DEBUG(llvm::dbgs() << "            FAILURE! Could not find state for "
                              "decrement.\n");
        return None;
      }
      DEBUG(llvm::dbgs() << "            SUCCESS! Found state for "
                            "decrement.\n");

      // Make sure the increment we are looking at is also matched to our
      // decrement.
      // Otherwise bail.
      if (!(*TDRefCountState)->second.isTrackingRefCountInst() ||
          !(*TDRefCountState)->second.containsInstruction(Increment)) {
        DEBUG(
            llvm::dbgs() << "            FAILURE! Not tracking instruction or "
                            "found increment that did not match.\n");
        return None;
      }

      // Add the decrement to the decrement to move set. If we don't insert
      // anything, just continue.
      if (!MatchSet.Decrements.insert(Decrement)) {
        DEBUG(llvm::dbgs()
              << "        SKIPPING! Already processed this decrement\n");
        continue;
      }

      // Collect the increment insertion point if it has one.
      for (auto InsertPt : (*TDRefCountState)->second.getInsertPts()) {
        MatchSet.IncrementInsertPts.insert(InsertPt);
      }
      NewDecrements.push_back(Decrement);
    }
  }

  return Flags;
}

Optional<MatchingSetFlags>
ARCMatchingSetBuilder::matchDecrementsToIncrements() {
  MatchingSetFlags Flags = {true, false};

  // For each increment in our list of new increments.
  //
  // FIXME: Refactor this into its own function.
  for (SILInstruction *Decrement : NewDecrements) {
    DEBUG(llvm::dbgs() << "    Looking up state for decrement: " << *Decrement);

    auto TDRefCountState = TDMap.find(Decrement);
    assert(TDRefCountState != TDMap.end() && "Catch this on debug builds.");
    if (TDRefCountState == TDMap.end()) {
      DEBUG(llvm::dbgs() << "        FAILURE! Could not find state for "
                            "increment!\n");
      return None;
    }

    DEBUG(llvm::dbgs() << "        SUCCESS! Found state for decrement.\n");

    // If we are not tracking a ref count inst for this increment, there is
    // nothing we can pair it with implying we should skip it.
    if (!(*TDRefCountState)->second.isTrackingRefCountInst()) {
      DEBUG(llvm::dbgs() << "    SKIPPING DECREMENT! State not tracking any "
                            "instruction.\n");
      continue;
    }

    // We need to be known safe over all increments/decrements we are matching
    // up
    // to ignore insertion points.
    bool TDIsKnownSafe = (*TDRefCountState)->second.isKnownSafe();
    DEBUG(llvm::dbgs() << "        KNOWNSAFE: "
                       << (TDIsKnownSafe ? "true" : "false") << "\n");
    Flags.KnownSafe &= TDIsKnownSafe;

    // We can only move instructions if we know that we are not partial. We can
    // still delete instructions in such cases though.
    bool TDIsPartial = (*TDRefCountState)->second.isPartial();
    DEBUG(llvm::dbgs() << "        PARTIAL: "
                       << (TDIsPartial ? "true" : "false") << "\n");
    Flags.Partial |= TDIsPartial;

    // Now that we know we have an inst, grab the decrement.
    for (auto IncIter : (*TDRefCountState)->second.getInstructions()) {
      SILInstruction *Increment = IncIter;
      DEBUG(llvm::dbgs() << "        Increment: " << *Increment);

      // Now grab the increment matched up with the decrement from the bottom up
      // map.
      // If we can't find it, bail we can't match this increment up with
      // anything.
      auto BURefCountState = BUMap.find(Increment);
      if (BURefCountState == BUMap.end()) {
        DEBUG(llvm::dbgs() << "            FAILURE! Could not find state for "
                              "increment.\n");
        return None;
      }

      DEBUG(
          llvm::dbgs() << "            SUCCESS! Found state for increment.\n");

      // Make sure the increment we are looking at is also matched to our
      // decrement.
      // Otherwise bail.
      if (!(*BURefCountState)->second.isTrackingRefCountInst() ||
          !(*BURefCountState)->second.containsInstruction(Decrement)) {
        DEBUG(
            llvm::dbgs() << "            FAILURE! Not tracking instruction or "
                            "found increment that did not match.\n");
        return None;
      }

      // Add the decrement to the decrement to move set. If we don't insert
      // anything, just continue.
      if (!MatchSet.Increments.insert(Increment)) {
        DEBUG(llvm::dbgs()
              << "    SKIPPING! Already processed this increment.\n");
        continue;
      }

      // Collect the decrement insertion point if we have one.
      for (auto InsertPtIter : (*BURefCountState)->second.getInsertPts()) {
        MatchSet.DecrementInsertPts.insert(InsertPtIter);
      }
      NewIncrements.push_back(Increment);
    }
  }

  return Flags;
}

/// Visit each retain/release that is matched up to our operand over and over
/// again until we converge by not adding any more to the set which we can move.
/// If we find a situation that we cannot handle, we bail and return false. If
/// we succeed and it is safe to move increment/releases, we return true.
bool ARCMatchingSetBuilder::matchUpIncDecSetsForPtr() {
  bool KnownSafeTD = true;
  bool KnownSafeBU = true;
  bool Partial = false;

  while (true) {
    DEBUG(llvm::dbgs() << "Attempting to match up increments -> decrements:\n");
    // For each increment in our list of new increments, attempt to match them
    // up
    // with decrements and gather the insertion points of the decrements.
    auto Result = matchIncrementsToDecrements();
    if (!Result) {
      DEBUG(llvm::dbgs() << "    FAILED TO MATCH INCREMENTS -> DECREMENTS!\n");
      return false;
    }
    if (!Result->KnownSafe) {
      DEBUG(llvm::dbgs() << "    NOT KNOWN SAFE!\n");
      KnownSafeTD = false;
    }
    if (Result->Partial) {
      DEBUG(llvm::dbgs() << "    IS PARTIAL!\n");
      Partial = true;
    }
    NewIncrements.clear();

    // If we do not have any decrements to attempt to match up with, bail.
    if (NewDecrements.empty())
      break;

    DEBUG(llvm::dbgs() << "Attempting to match up decrements -> increments:\n");
    Result = matchDecrementsToIncrements();
    if (!Result) {
      DEBUG(llvm::dbgs() << "    FAILED TO MATCH DECREMENTS -> INCREMENTS!\n");
      return false;
    }
    if (!Result->KnownSafe) {
      DEBUG(llvm::dbgs() << "    NOT KNOWN SAFE!\n");
      KnownSafeBU = false;
    }
    if (Result->Partial) {
      DEBUG(llvm::dbgs() << "    IS PARTIAL!\n");
      Partial = true;
    }
    NewDecrements.clear();

    // If we do not have any increment to attempt to match up with again, bail.
    if (NewIncrements.empty())
      break;
  }

  bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU);
  if (UnconditionallySafe) {
    DEBUG(llvm::dbgs() << "UNCONDITIONALLY SAFE! DELETING INSTS.\n");
    MatchSet.IncrementInsertPts.clear();
    MatchSet.DecrementInsertPts.clear();
  } else {
    DEBUG(llvm::dbgs() << "NOT UNCONDITIONALLY SAFE!\n");
  }

  bool HaveIncInsertPts = !MatchSet.IncrementInsertPts.empty();
  bool HaveDecInsertPts = !MatchSet.DecrementInsertPts.empty();

  // We should not have the case which retains have to be anchored topdown and
  // releases do not have to be bottomup, or vice-versa.
  assert(HaveIncInsertPts == HaveDecInsertPts &&
         "Asymmetric insertion points for retains and releases");

  // If we have insertion points and partial merges, return false to avoid
  // control dependency issues.
  if ((HaveIncInsertPts || HaveDecInsertPts) && Partial) {
    DEBUG(llvm::dbgs() << "Found partial merge and insert pts. Bailing!\n");
    return false;
  }

  // If we do not have any insertion points but we do have increments, we must
  // be eliminating pairs.
  if (!HaveIncInsertPts && !MatchSet.Increments.empty())
    MatchedPair = true;

  // Success!
  DEBUG(llvm::dbgs() << "SUCCESS! We can move, remove things.\n");
  return true;
}
<|endoftext|>